Java 将文本转换为字符串数组,找到在第二个位置发送的字符串,并将其替换为第三个位置的字符串
关于这个问题,我完全不知道该怎么办。我想做的是从一串单词中提取一个单词,然后用另一个字符串中的一个单词替换它。 例如,提示我的示例之一是:Java 将文本转换为字符串数组,找到在第二个位置发送的字符串,并将其替换为第三个位置的字符串,java,string,replace,split,Java,String,Replace,Split,关于这个问题,我完全不知道该怎么办。我想做的是从一串单词中提取一个单词,然后用另一个字符串中的一个单词替换它。 例如,提示我的示例之一是: //changeWords("Hi nice to meet you", "hi", "hello") returns ["hello", "nice", "to", "meet", "you"]
//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;
}
诚然,我的代码不太详细,也不太可能找到解决方案,但我想从我的代码中得到一些指导。谢谢您的帮助。正如@D George所说,您需要使用循环进行循环,并使用.equals()方法比较字符串。您可以修改代码,使其看起来像这样。。。 或者使用string对象的.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.replace(find, replace);
}
find
,一种简单的方法是将(?i)
与正则表达式一起使用import java.util.Arrays;
class Main {
public static void main(String[] args) {
// Test
System.out.println(Arrays.toString(changeWords("Hi nice to meet you", "hi", "hello")));
}
public static String[] changeWords(String text, String find, String replace) {
return text.replaceAll("(?i)(" + find + ")", replace).split(" ");
}
}
[hello, nice, to, meet, you]
输出:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
// Test
System.out.println(Arrays.toString(changeWords("Hi nice to meet you", "hi", "hello")));
}
public static String[] changeWords(String text, String find, String replace) {
return text.replaceAll("(?i)(" + find + ")", replace).split(" ");
}
}
[hello, nice, to, meet, you]
不要在第0个位置检查单词,而是在字符串数组中循环并比较每个单词。一旦找到匹配项,用单词替换单词[i]=替换并跳出循环。您必须使用
.equals()
,而不是=
,来比较java中的对象。您的思路是正确的,但现在我的程序只替换每个单词的第一个实例,正如Arvind Kumar Avinash指出的,不考虑不区分大小写的示例。我发布的示例当前返回“你好,很高兴见到你”。我正在咨询的一位助手告诉我,数组单词的大小是问题的一部分。您可以使用.equalsIgnoreCase()方法以不区分大小写的方式查找匹配项,非常感谢。我和另一个学生商量了一下以帮助完成代码,但是你提供的帮助在解决它方面起了很大的作用!