简体   繁体   中英

Replace a word in string if it is found in an array

For example the user types: The fruit apple is my favourite. I'd like to return: The fruit ***** is my favourite.

But my code only returns the first word.

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


}

Way of inputting is not correct

It should be

String s = scan.nextLine();

rather than scan.next();

With s = scan.next();

s will only get initialized as "The"

Also put a break once you found the element. This will make sure to come out of the loop when element is found and improve the code performance.

matchFound = true;
break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM