在Java中,在字符串的子字符串之间插入字符
我有一个单词列表,存储在一个单词列表中在Java中,在字符串的子字符串之间插入字符,java,string,Java,String,我有一个单词列表,存储在一个单词列表中 private String[]words=新字符串[]{“世界”,“你”} 然后我有一个字符串,helloWorld private String helloWorld=“你好吗?” 我想创建一个函数,该函数将接受一个字符串(在本例中为helloWorld),它将不区分大小写地查看单词列表中是否存在任何字符串。如果有,它将在匹配字符串的每个字母之间放置一个*字符 例如,输出将是 Hello w*o*r*l*d你好吗?因为world和you都在列表中 传递
private String[]words=新字符串[]{“世界”,“你”}代码>
然后我有一个字符串,helloWorld
private String helloWorld=“你好吗?”代码>
我想创建一个函数,该函数将接受一个字符串(在本例中为helloWorld),它将不区分大小写地查看单词
列表中是否存在任何字符串。如果有,它将在匹配字符串的每个字母之间放置一个*
字符
例如,输出将是
Hello w*o*r*l*d你好吗?
因为world
和you
都在列表中
传递“Hello”
只会返回未修改的字符串“Hello”
,因为字符串中没有任何内容在单词中
我该怎么做呢?我尝试对每个单词的字符串硬编码一个.replaceAll()调用,但随后我丢失了字符串的大小写。例如,“你好,世界你好吗?”
变成了“你好,w*o*r*l*d,y*o*u怎么样?”
此代码:
private static String[] words = new String[]{"world", "you"};
private static String helloWorld = "Hello world how are you?";
public static String getHello() {
String s = helloWorld;
for (String word : words) {
int index = s.toLowerCase().indexOf(word.toLowerCase());
if (index >= 0) {
String w = s.substring(index, index + word.length());
StringBuilder sb = new StringBuilder();
sb.append(s.substring(0, index));
for (int i = 0; i < w.length(); i++) {
sb.append(w.charAt(i));
if (i < w.length() - 1)
sb.append("*");
}
sb.append(s.substring(index + w.length()));
s = sb.toString();
}
}
return s;
}
public static void main(String[] args) {
System.out.println(getHello());
}
String helloWorld=“你好,世界你好”;
字符串[]单词=新字符串[]{“世界”,“你”};
字符串newWord=“”;
字符串字1[]=helloWorld.split(“”);
for(int i=0;i 对于(int j=0;jPost您已经尝试过的内容。您可以使用String.equalsIgnoreCase()并检查每项工作(空格分隔单词)。然后只需删除匹配的单词并将其替换为m*a*r*k*e*d单词。我认为这个问题不是关于语言功能,而是关于让其他人完成工作的此类问题。
Hello w*o*r*l*d how are y*o*u?
String helloWorld = "hello world how are you ";
String[] words = new String[]{"world", "you"};
String newWord = "";
String words1[]= helloWorld.split(" ");
for (int i = 0;i< words.length;i++){
for (int j=0;j<words1.length;j++){
if (words1[j].equals(words[i])){
for (int k = 0 ; k < words1[j].length(); k++){
char character = words1[j].charAt(k);
newWord+=character;
newWord += "*";
}
words1[j] = newWord;
newWord= "";
}
}
}
String str = Arrays.toString(words1);
System.out.println(str);