我有一个单词列表,存储在一个单词列表中。
private String[] words = new String[]{"world", "you"};
然后我有一个字符串helloWorld
private String helloWorld = "Hello world how are you?";
我想创建一个将接受字符串的函数(在本例中为helloWorld),它看起来不区分大小写,以查看words
列表中是否存在任何字符串。如果存在,它将在匹配字符串的每个字母之间放置一个*
字符。
例如输出将是
Hello w*o*r*l*d how are y*o*u?
,因为world
和you
都在列表中。
传递"Hello"
只会返回未修改的字符串"Hello"
,因为字符串words
中没有任何内容。
我将如何去做?我曾尝试对每个单词的字符串进行.replaceAll()调用的硬编码,但随后我丢失了字符串的大小写。例如。 "Hello world how are you?"
成为"hello w*o*r*l*d how are y*o*u?"
答案 0 :(得分:0)
此代码:
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());
}
打印:
Hello w*o*r*l*d how are y*o*u?
答案 1 :(得分:0)
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);
}