【问题标题】:Turn a text into an array of strings, find the string that is sent in the second position, and replace it with the string in the third position把一个文本变成一个字符串数组,找到第二个位置发送的字符串,用第三个位置的字符串替换
【发布时间】:2021-03-21 08:54:25
【问题描述】:

我完全不知道该去哪里解决这个问题。我想做的是从一串单词中取出一个单词,然后用另一个字符串中的一个单词替换它。 例如,提示我的示例之一是:

//changeWords("Hi nice to meet you", "hi", "hello") returns ["hello", "nice", "to", "meet", "you"]

这是我目前输入的内容:

public static String[] changeWords(String text, String find, String replace)
  {
     String[] words = new String[0];
     words = text.split(" ");
     if (words[0] == find) {
       words[0].set(replace);
     }
    return words;
  }

诚然,我的代码并不太详细,也不太可能找到解决方案,但我想要一些关于从我拥有的东西着手的指导。感谢您的帮助。

【问题讨论】:

  • 不是检查第 0 个位置的单词,而是遍历字符串数组并比较每个单词。找到匹配项后,使用 words[i] = replace 替换单词并跳出循环。
  • 你必须使用.equals()而不是==比较java中的对象。

标签: java string replace split


【解决方案1】:

正如@D George 所说,您需要使用循环进行循环并使用 .equals() 方法来比较字符串。你可以修改你的代码看起来像这样...... 或使用字符串对象的 .replaceFirst() 方法替换搜索字符串的第一次出现。试试这个

public static String[] changeWords(String text, String find, String replace)
  {
     String[] words = new String[0];
     words = text.split(" ");
     for(int i = 0; i < words.length; i++){
       if (words[i].equalsIgnoreCase(find)) {
         words[i]=replace;
         break;
       }
     }
    return words;
  }

或者这个

public static String[] changeWords(String text, String find, String replace)
{
   return text.replaceFirst(find, replace);
}

上述方法非常适合您只想替换第一次出现的搜索字符串的情况。如果要替换所有出现的搜索字符串,则不需要使用数组,因为字符串对象带有替换方法。你可以这样做来替换所有出现的地方:

public static String[] changeWords(String text, String find, String replace)
  {
    return text.replace(find, replace);
  }

【讨论】:

  • 你在正确的轨道上,但现在我的程序只是替换每个单词的第一个实例,就像 Arvind Kumar Avinash 指出的那样,不考虑不区分大小写的例子。我发布的示例当前正在返回“Hi nice to meet you”。我正在咨询的一位助手告诉我,数组单词的大小是问题的一部分。
  • 您可以使用 .equalsIgnoreCase() 方法以不区分大小写的方式查找匹配项
  • 非常感谢。我咨询了另一位学生以帮助完成代码,但您提供的内容对解决问题有很大帮助!
猜你喜欢
  • 2019-09-22
  • 2021-04-09
  • 2016-03-29
  • 2017-03-26
  • 2020-02-14
  • 1970-01-01
  • 2014-11-04
  • 2013-04-10
  • 2014-03-07
相关资源
最近更新 更多