请实现一个函数,把字符串 s
中的每个空格替换成"%20"。
class Solution { public: string replaceSpace(string s) { int len = s.size(); int count = 0; //统计空格数量 for (char& c : s) { if (c == ' ') count++; } //定义s_copy长度 int s_len = len + count * 2; std::string s_copy; s_copy.resize(s_len); //遍历修改 int i = len-1; int j = s_len-1; while (i>=0) { if (s[i] == ' ') { s_copy[j] = '0'; s_copy[j - 1] = '2'; s_copy[j - 2] = '%'; j = j - 3; } else { s_copy[j] = s[i]; j = j - 1; } i = i - 1; } return s_copy; } };
已经造好的轮子:
return s.replace(" ","%20");
标签:count,string,Offer,int,05,len,空格,copy
From: https://www.cnblogs.com/lihaoxiang/p/16791185.html