Offer to prove safety
Please implement a function, a string to replace each space to "20%." For example, when the string is We Are Happy. After the string is replaced after We% 20Are% 20Happy.
replaceSpace与replaceSpace2两种方法。
import java.util.Arrays;
public class Space {
public static void main(String[] args) {
StringBuffer s = new StringBuffer("sda sad aa123");
String res = replaceSpace2(s);
System.out.println(res);
}
public static String replaceSpace(StringBuffer str) {
if (str == null) {
return "";
}
String ss = new String();
ss.charAt(1);
ss = str.toString().replace( " " , "%20" );
return ss;
}
public static String replaceSpace2(StringBuffer str) {
if (str == null) {
return "";
}
int black;
black = 0;
char[] chars = str.toString().toCharArray();
for(int i=0;i<chars.length-1;i++){
if(chars[i] == ' '){
black++;
}
}
char[] new_chars = new char[str.length()+2*black];
int num;
int num2;
num = str.length()+2*black-1;
num2 = str.length()-1;
while(num2>=0){
if(chars[num2] == ' '){
new_chars[num--] = '0';
new_chars[num--] = '2';
new_chars[num--] = '%';
num2--;
}
else {
new_chars[num--] = chars[num2--];
}
}
String ss = String.valueOf(new_chars);
return ss;
}
}