how can I replace a specific word from user input and display it as an asterisk. This is my code.
String[] filteredWords = ["apple", "banana", "orange"];
private String convertWord(String input) {
StringBuilder asterisk = new StringBuilder();
for (String filter: filteredWords) {
if (input.toLowerCase().contains(filter)) {
for (int i = 0; i < filter.length(); i++) {
asterisk.append("*");
}
input = input.replace(filter, asterisk.toString());
}
}
return input;
}
for example the user input or type "This is apple and not orange", the expected output would be "This is ***** and not ******".
but my problem here is when the user type (with a character casing) "This is Apple and not oRaNGE" or "This is aPpLe and not Orange" the output is not changing. The word apple and orange are not being replace with an asterisk.
any help is appreciated. Thank you!
Python String replace() MethodThe replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.
I like using regex replacement here, with an alternation containing all your search terms:
String[] filteredWords = { "apple", "banana", "orange" };
String regex = "(?i)\\b(?:" + String.join("|", filteredWords) + ")\\b";
private String convertWord(String input) {
input = input.replaceAll(regex, "*");
return input;
}
convertWord("Apple watermelon ORANGE boot book pear banana");
The output from the above method call is:
* watermelon * boot book pear *
String[] filteredWords = ["apple", "banana", "orange"];
private static String convertWord(String input) {
StringBuilder asterisk = new StringBuilder();
String inputInLower = input.toLowerCase();
for (String filter: filteredWords) {
if (inputInLower.contains(filter)) {
for (int i = 0; i < filter.length(); i++) {
asterisk.append("*");
}
inputInLower = inputInLower.replace(filter, asterisk.toString());
asterisk.setLength(0);
}
}
return inputInLower;
}
There was 2 problems I found in your code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With