(java版剑指offer)JZ5 替换空格(方法二:遍历法+StringBuilder拼接法)
替换空格
https://www.nowcoder.com/practice/0e26e5551f2b489b9f58bc83aa4b6c68?tpId=265&tqId=39209&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D13&difficulty=undefined&judgeStatus=undefined&tags=&title=
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串
*/
//多线程操作字符串缓冲区下操作大量数据 StringBuffer;
//单线程操作字符串缓冲区下操作大量数据 StringBuilder。以上两者的字符串可变
//而单纯的String,字符串长度不可变
public String replaceSpace(String s) {
//实例化StringBuilder字符串类
//遍历
//字符为空格,则在StringBuilder后面附加上"%20"
//否则直接拼接
//输出字符串
StringBuilder stringbuilder = new StringBuilder();
for (int i=0; i<s.length(); i++){
if(s.charAt(i) == ' '){
stringbuilder.append("%20");
}else{
stringbuilder.append(s.charAt(i));
}
}
return stringbuilder.toString();
}
}