首页 > 解决方案 > 使用 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

标签: java

解决方案


对不起,之前我没有看到你到底想要什么。我修改了一点你的代码。我使用 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());
}

祝你们好运!


推荐阅读