Search code examples
javauppercaselowercase

How can I convert all forms of a specific word in a String to lowercase?


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..


Solution

  • 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.