java - 如果在数组中找到,则替换字符串中的单词

标签 java arrays substring

例如用户类型:水果苹果是我的最爱。 我要回:水果*****是我的最爱。

但我的代码只返回第一个单词。

    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/

相关文章:

java - Java中将输入作为字符串并限制用户不能输入整数

java - 如何重写Java中的fillOval函数?

javascript - 从数组中删除的最有效方法?

c# - 如何在C#中通过正则表达式匹配由给定子字符串构造的字符串

windows - 批处理文件 : Is it possible to extract a substring where the index is a variable?

java - java中如何截取各种操作系统的屏幕截图?

java - 如何使用 Java 读取已写入的文件

java - 使用 System.arrayCopy 复制原始类型的数组,是浅的还是深的?

c++ - 错误 : 'begin' was not declared in this scope

java - 使用 Switch 语句检查字符串中的子字符串