Reputation: 1627
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!
Upvotes: 5
Views: 542
Reputation: 21
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
Upvotes: 2
Reputation: 521
I think the must easy way it just add in xml option that user can insert only small latter, because if I understand right, you don't carry about latter, you work with words.
So how you can do i, you can add in xml fist line or seconds code line in your java class.
android:digits="abcdefghijklmnopqrstuvwxyz1234567890 "
EditText userText = findViewById(R.id.userText);
String input;
input = userText.getText().toString();
input = input.toLowerCase();
Upvotes: 0
Reputation: 520958
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 *
Upvotes: 6