Java will replace a specific row in an 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 spaces in the lines inside the array above with% 20 to do it like

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

how to do it?

+4
source share
6 answers

Iterate through the array and replace each entry with your encoded version.

So, suppose you are really only looking for URL compatible strings:

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

To match current Java, you must specify an encoding — however, it must always be UTF-8 .

If you want a more general version, do what everyone else offers:

 for (int index =0; index < test.length; index++){ test[index] = test[index].replace(" ", "%20"); } 
+8
source

Try using String#relaceAll(regex,replacement) ; untested, but this should work:

 for (int i=0; i<test.length; i++) { test[i] = test[i].replaceAll(" ", "%20"); } 
+3
source

Here's a simple solution:

 for (int i=0; i < test.length; i++) { test[i] = test[i].replaceAll(" ", "%20"); } 

However, it looks like you are trying to avoid these strings for use in the url, in which case I suggest you look for a library that does this for you.

+2
source

for each row you will do replaceAll ("\\ s", "% 20")

+1
source
 String[] test={"hahaha lol","jeng jeng jeng","stack overflow"}; for (int i=0;i<test.length;i++) { test[i]=test[i].replaceAll(" ", "%20"); } 
0
source

Straight from Java docs ... String java docs

You can do String.replace ('toreplace', 'replacement').

Iterate through each element of an array with a for loop.

0
source

Source: https://habr.com/ru/post/1392967/


All Articles