Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace certain string in array of strings

let's say I have this string array in java

String[] test = {"hahaha lol", "jeng jeng jeng", "stack overflow"};

but now I want to replace all the whitespaces in the strings inside the array above to %20, to make it like this

String[] test = {"hahaha%20lol", "jeng%20jeng%20jeng", "stack%20overflow"};

How do I do it?

like image 289
imin Avatar asked Jan 25 '12 15:01

imin


1 Answers

Iterate over the Array and replace each entry with its encoded version.

Like so, assuming that you are actually looking for URL-compatible Strings only:

for (int index =0; index < test.length; index++){
  test[index] = URLEncoder.encode(test[index], "UTF-8");
}

To conform to current Java, you have to specify the encoding - however, it should always be UTF-8.

If you want a more generic version, do what everyone else suggests:

for (int index =0; index < test.length; index++){
    test[index] = test[index].replace(" ", "%20");
}
like image 99
Urs Reupke Avatar answered Oct 20 '22 22:10

Urs Reupke