【问题标题】:How to replace words instead of the whole sentence with contains and replace methods?如何用包含和替换方法替换单词而不是整个句子?
【发布时间】:2014-05-24 12:55:49
【问题描述】:

我已经编写了这段代码,但我遇到了问题。当我写“替换别的东西”时,我想打印“嗨别的东西”。我该怎么做?

import java.util.Scanner;
public class replace something
{
    public static void main(String[] args)
    {
        Scanner cumle = new Scanner(System.in);
        System.out.println("Enter the sentence u want to replace :");
        String str1 = cumle.next();
        if (str1.contains("replace"))
        {
            str1 = str1.replace("replace", "Hi");
            System.out.println("Replaced Sentence: " + str1);
        }
        else
        {
            System.out.println("Sentence doesn't contains that...");
        }

    }

}

【问题讨论】:

  • 检查您正在打印的字符串...
  • 详细说明,修复错字System.out.println("Replaced Sentence: " + str);

标签: java string replace contains


【解决方案1】:

您打印的是str1,而不是str

改变这个:

System.out.println("Replaced Sentence: " + str1);

到这里:

System.out.println("Replaced Sentence: " + str);

【讨论】:

    【解决方案2】:

    首先,你必须用nextLine() 读取整行,因为next() 只读取下一个标记。

    另外,如果你想修改原始字符串,你必须将replace()的结果赋值给str1

    str1 = str1.replace("replace", "Hi");
    

    代码:

    Scanner cumle = new Scanner(System.in);
    System.out.println("Enter the sentence u want to replace :");
    String str1 = cumle.nextLine();
    
    if (str1.contains("replace")) {
        str1 = str1.replace("replace", "Hi");
        System.out.println("Replaced Sentence: " + str1);
    } else {
        System.out.println("Sentence doesn't contains that...");
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 2014-11-02
      • 2021-10-02
      相关资源
      最近更新 更多