java - 字符串操作 - 将第二个单词的字符删除到第一个单词
问题描述
输入两个字:计算机程序
结果:可爱
the character of the second word of the users input is deleted on the first word of the input in java. Leaving "cute"
想过使用 replaceAll 但无法使其工作。
String sentence;
Scanner input = new Scanner(System.in);
System.out.println("Enter 2 words: ");
sentence = input.nextLine();
String[] arrWrd = sentence.split(" ");
String scdWrd = arrWrd[1];
String fnl = arrWrd[0].replaceAll(scdWrd, "");
System.out.println(fnl);
解决方案
.replaceAll
需要一个正则表达式,所以基本上你在这里所做的是你正在搜索整个“程序”单词并替换它而不是它的字符,所以你只需要在你的 scdWrd 中添加括号让它知道你想要替换字符:
String scdWrd = "[" + arrWrd[1] + "]";
推荐阅读
- graphql - Shopify graphql 客户创建
- python - 无法使用 Python Pyautogui 以管理员身份打开 CMD
- javascript - React FilePond 预览 [ 文件海报 ] 不工作
- scala - 如何使用 SparkSQL 从数据框列中获取值?
- python - GPIO控制在while true:
- arrays - 创建具有固定数量元素但仍少于固定数量的随机生成数组
- html - CSS 自定义复选框
- html - 为什么 div 会越过图像?
- javascript - 以 PDF 格式下载 HTML 表格
- python - 如何从存在轻微背景的图像中提取文本?