/**
* 空格替换,在原有的字符串上进行修改
* @Description
*/
public class Test03_2 {
public String replaceSpace(StringBuffer s) { //因为String为不可变对象,这里采用StringBuffer
if (s == null || s.length() <= 0){
return null;
}
int len = s.length();
int tailIndex = len - 1;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' '){
len += 2;
}
}
s.setLength(len);
int tailIndexNew = len - 1;
while (tailIndexNew > tailIndex){
if (s.charAt(tailIndex) != ' ') {
s.setCharAt(tailIndex--, s.charAt(tailIndexNew));
} else {
s.setCharAt(tailIndex--, '0');
s.setCharAt(tailIndex--, '2');
s.setCharAt(tailIndex--, '%');
}
tailIndex--;
}
return s.toString();
}
public static void main(String[] args) {
System.out.println(new Test03_2().replaceSpace(new StringBuffer("we are family")));
System.out.println(new Test03_2().replaceSpace(new StringBuffer(" ")));
}
}
剑指Offer-02-空格替换(2)
最新推荐文章于 2022-04-05 13:20:38 发布