Reputation: 21
I'm in my first semester in coding and completely stuck on this one.
I want to get all forms of a word (ex: HeLLo, hEllO, heLlo, ...) to change to lowercase and don't know how to get there without writing a condition for every single variation in my file. I have many words I have to convert to either lowercase or uppercase so I realized that there must be a better way of doing but can't figure out which.
Is there a way to get all of these variations at once and convert them to lowercase?
Input = " HeLlo this is my program called HELLO "
Output = " hello this is my program called hello "
I've only tried:
word.replace("HELLO", "hello");
word.replace("Hello", "hello"); and so on..
Upvotes: 1
Views: 722
Reputation: 199205
Idea:
HeLlo There heLLO WorlD
-> hello there hello world
"hello"
-> [0, 12]
hello There hello WorlD
pseudo
String toLower(String input, String replacement) {
indices = input.toLower().allIndecesOf(replacement)
result = input.clone()
for i in indices {
result = result.replace( i, replacement )
}
return result
}
Upvotes: 0
Reputation: 2906
You can use java.util.regex.Pattern with the CASE_INSENSITIVE Option:
Pattern pattern = Pattern.compile(Pattern.quote("hallo"), Pattern.CASE_INSENSITIVE);
String test = "Hallo FoO HallO BaR HaLLo BAz";
String replaced = pattern.matcher(test).replaceAll("hallo");
// Output: hallo FoO hallo BaR hallo BAz
Upvotes: 2
Reputation: 857
For a regex solution:
word = word.replaceAll("(?i)hello", "hello");
This is a "case-insensitive" replacement; i.e., all instances of "hello" regardless of case (Hello, HeLlO, HELLO, etc.) will be replaced with "hello".
I found this article to be particularly helpful when learning regex. Here's a live working example.
Upvotes: 7
Reputation: 216
Providing that your input text is the value 'text' (you can make the variable names whatever you want), it should output the correct string. You can add words you want to change to lowercase and uppercase (make sure when you add them they are in lower case)
String text = "Hello I am No GoodBYE";
String[] lowercase = {"hello", "goodbye"};
String[] uppercase = {"no", "yes"};
String[] split_string = text.split(" ");
for (int i=0;i < split_string.length;i++){
for (String low:lowercase){
if (split_string[i].toLowerCase().equals(low)){
split_string[i] = split_string[i].toLowerCase();
}
}
for (String upper:uppercase){
if (split_string[i].toLowerCase().equals(upper)){
split_string[i] = split_string[i].toUpperCase();
}
}
}
String final_result = "";
for(String word:split_string){
final_result = final_result + " " + word;
}
System.out.println(final_result);
Upvotes: 1
Reputation: 216
word.toLowerCase()
or for the opposite
word.toUpperCase()
I hope this helps!
Upvotes: 2