将字符串中的所有空格替换成%20
package array_2_3;
import java.util.Arrays;
public class Demo_5 {
public static void main(String[] args) {
String str = "we are happy.";
Demo_5 demo = new Demo_5();
int count = demo.theNumOfSpace(str);
String[] res = demo.replace(str, count);
System.out.println(Arrays.toString(res));
}
public String[] replace(String str, int count) {
int finalLen = str.length() + 2*count;
String[] array = new String[finalLen];
int p1 = str.length() - 1;
int p2 = finalLen - 1;
while (p1 >= 0) {
if (" ".equals(str.charAt(p1)+"")){
array[p2--] = "0";
array[p2--] = "2";
array[p2--] = "%";
}else {
array[p2--] = str.charAt(p1)+"";
}
p1--;
}
return array;
}
public int theNumOfSpace(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (" ".equals(str.charAt(i)+"")) {
count++;
}
}
return count;
}
}