[Solved] Write a Java program that takes two inputs: 1. text 2. a word or a phrase [closed]


class GFG {
    static String censor(String text,
                         String word) {
        String stars = "";
        for (int i = 0; i < word.length(); i++)
            if (word.charAt(i) != ' '){
                stars += '#';
            }else {
                stars += ' ';
            }
        text = text.replaceAll(word,stars);
        return text;
    }

    public static void main(String[] args) {
        String extract = "Lorem ipsum dolor sit amet, consectetur adipiscing elit , sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." + "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
        String cen = "consectetur adipiscing elit";
        System.out.println(censor(extract, cen));
    }
}

I tried to keep the code similar to yours, i kept the building part of the * strings (it can be done better) and just used text.replaceAll(‘String to be replaced’,’* string’) that change all the occurencies with the first argument with the second.

let me know if this works for you.

Btw the problem in your code was that you were splitting on the words but you wanted to change a whole substring.
If your need was to change the single occurrencies of the words that you are giving you should’ve splitted the words in an array, then you had to cycle on the array and do a replace for each word.

0

solved Write a Java program that takes two inputs: 1. text 2. a word or a phrase [closed]