How to change spaces to underscore and make string case insensitive?

JavaAndroidStringCase InsensitiveReplaceall

Java Problem Overview


I have following question. In my app there is a listview. I get itemname from listview and transfer it to the webview as a string. How to ignore case of this string and change spaces to underscores?

For example: String itemname = "First Topic". I transfer it to the next activity and want to ignore case and change space to underscore (I want to get first_topic in result). I get "itemname" in webviewactivity and want to do what I've described for following code:

String filename = bundle.getString("itemname") + ".html";

Please, help.

Java Solutions


Solution 1 - Java

use replaceAll and toLowerCase methods like this:

myString = myString.replaceAll(" ", "_").toLowerCase()

Solution 2 - Java

This works for me:

itemname = itemname.replaceAll("\\s+", "_").toLowerCase();

replaceAll("\\s+", "_") replaces consecutive whitespaces with a single underscore.

"first topic".replaceAll("\\s+", "_") -> first_topic

"first topic".replaceAll(" ", "_") -> first__topic

Solution 3 - Java

You can use the replaceAll & toLowerCase methods but keep in mind that they don't change the string (they just return a modified string) so you need to assign the back to the variable, eg.

String itemname = bundle.getString("itemname"); 
itemname = itemname.replaceAll(" ", "_").toLowerCase(); 
String filename = itemname + ".html";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSabreView Question on Stackoverflow
Solution 1 - Javashift66View Answer on Stackoverflow
Solution 2 - JavaChris OciepaView Answer on Stackoverflow
Solution 3 - JavaZariusView Answer on Stackoverflow