例如用户类型:水果苹果是我的最爱。 我要回:水果*****是我的最爱。
但我的代码只返回第一个单词。
public static void main(String[] args) {
System.out.print("Type someting: ");
Scanner scan = new Scanner(System.in);
String s = scan.next();
String [] myArray = {"apple", "banana", "strawberry"};
boolean matchFound = false;
for (int i = 0; i < myArray.length; i++) {
if (s.toLowerCase().contains(myArray[i].toLowerCase())){
String beep = String.join("", Collections.nCopies(myArray[i].length(), "*"));
String result = s.replaceAll(myArray[i].toLowerCase(), beep);
System.out.println(result);
matchFound = true;
}
}
if (matchFound == false){
System.out.println(s);
}
}
最佳答案
输入方式不正确
应该是
String s = scan.nextLine();
而不是 scan.next();
用 s = scan.next();
s 只会被初始化为“The”
关于java - 如果在数组中找到,则替换字符串中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45701010/