java - 使用 Scanner 类将所有出现的字符串替换为另一个
问题描述
我想用一个Scanner
类扫描一个字符串,我想用“不是”替换每个“是”字,期望嵌入的“是”像“这个”例如
good morning this is my name
变成good morning this is not my name
我写的代码片段
public static void main(String[] args) {
String chaine="good morning this is my name";
Scanner sc=new Scanner(chaine);
while(sc.hasNext()) {
String word=sc.next();
if(word.equals("is"))
chaine=chaine.replace(word, "is not");
}
System.out.println(chaine);
}
当我执行这个程序时它打印:
good morning this not is not my name
但我想打印早上好this is not my name
解决方案
对不起,之前我没有看到你到底想要什么。我修改了一点你的代码。我使用 StringBuilder 来存储单词的各个部分,然后关闭 Scanner。
public static void main(String[] args) {
String chaine="good morning this is my name";
Scanner sc=new Scanner(chaine);
StringBuilder sb = new StringBuilder();
while(sc.hasNext()) {
String word=sc.next();
if(word.equals("is"))
{
sb.append("is not");
}
else
{
sb.append(word);
}
//Add space after every added word.
sb.append(" ");
}
sc.close();
String result = sb.toString();
//Call trim to remove the space after the last word
System.out.println(result.trim());
}
祝你们好运!
推荐阅读
- c - 使用 char 和 int 变量在 c 中创建数值表达式
- dotnetnuke - DNN 8 用户无法重置密码
- java - 重定向只显示链接而不是让用户链接
- .net - How to check programmatically if .NET 4.7 Target Pack is installed?
- node.js - typescript express typeorm createconnection
- amazon-web-services - 如何使用代码切换“将相同设置应用于全局二级索引”?
- java - 开始时的 LeanFT 空指针
- sql - 可以从其他条目添加的具有缺失值的 SQL 查询
- angular - Angular2 和 ag-grid - 如何固定过滤器菜单
- java - 如何在画布上检索信息