【问题标题】:Replace a word in string if it is found in an array如果在数组中找到,则替换字符串中的单词
【发布时间】:2018-01-23 20:32:39
【问题描述】:

例如用户输入:水果苹果是我最喜欢的。 我想回来:水果*****是我的最爱。

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

    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);
    }


}

【问题讨论】:

  • 找不到匹配项为什么要打印?

标签: java arrays substring


【解决方案1】:

输入方式不对

应该是

String s = scan.nextLine();

而不是scan.next();

用 s = scan.next();

s 只会被初始化为“The”

【讨论】:

  • 多么简单的解决方案。 :) 谢谢!
【解决方案2】:

一旦你找到了这个元素,也要休息一下。这将确保在找到元素时退出循环并提高代码性能。

matchFound = true;
break;

【讨论】:

  • 其实我想检查每一个元素,如果发现也要改变。
  • 你是说'myArray'可以复制水果吗?如果是,则无需中断。如果没有重复,那么 break 会很好。因为如果你找到了一个元素,那么下次你就不会得到它了。
  • 我的意思是,如果用户键入两个或多个等于数组中的一个的单词,那么我也想用 * 替换它们。
猜你喜欢
  • 1970-01-01
  • 2020-07-04
  • 2013-02-18
  • 1970-01-01
  • 2012-12-04
  • 1970-01-01
  • 2017-05-15
  • 1970-01-01
  • 2020-11-09
相关资源
最近更新 更多