55

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.

Anson VanDoren
  • 956
  • 1
  • 12
  • 22
Sabre
  • 4,131
  • 5
  • 36
  • 57

3 Answers3

131

use replaceAll and toLowerCase methods like this:

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

Anson VanDoren
  • 956
  • 1
  • 12
  • 22
shift66
  • 11,760
  • 13
  • 50
  • 83
  • Thanks, but I have no result. I use it in activity as `String itemname = bundle.getString("itemname"); itemname.replaceAll(" ", "_").toLowerCase();` And then `String filename = itemname + ".html";` May be it's not right. Please, have a look. – Sabre Feb 27 '12 at 07:33
  • 4
    u need to write it as itemname = itemname.replaceAll(" ", "_").toLowerCase(); – everconfusedGuy Feb 27 '12 at 07:41
  • 1
    @naini answered... these methods are not modifying the string they just return a new modified string so you should assign the new value. – shift66 Feb 27 '12 at 07:45
39

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

Abdull
  • 26,371
  • 26
  • 130
  • 172
Chris Ociepa
  • 694
  • 6
  • 12
6

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";
Zarius
  • 61
  • 1
  • Doh, question was answered as a comment to previous answer whilst I typed (and I guess I should have posted as a comment - new to StackOverflow) – Zarius Feb 27 '12 at 07:48