字符串中的每个空格替换成“%20”
替换空格
http://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423
solution 1:
public class Solution { public String replaceSpace(StringBuffer str) { return str.toString().replace(" ", "%20"); } }
solution 2:
public String replace(StringBuffer str) { int n = str.length(); for(int i=0; i<n; i++) { if(str.charAt(i) == ' ') { n += 2; str.replace(i, i+1, "%20"); } } return str.toString(); }
C++ solution:
class Solution { public: void replaceSpace(char* str, int length) { string str_cpp(str); string::size_type pos = 0; while ((pos = str_cpp.find(' ')) != string::npos) { str_cpp.replace(pos, 1, "%20"); } str = strcpy(str,str_cpp.c_str()); } };