简单题目 不用模板 直接手动记录
1.JZ5 替换空格
请实现一个函数,将一个字符串s中的每个空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
数据范围:0 \le len(s) \le 1000 \0≤len(s)≤1000 。保证字符串中的字符为大写英文字母、小写英文字母和空格中的一种。
2.思路
继续平民思路,遍历字符串,碰到正常字符直接加入新字符串,碰到空格,给新字符串加入”%20“即可
3.代码
class Solution {
public:
string replaceSpace(string s) {
string ans="";
for(char world : s)
{
if(world!=' ')
ans+=world;
else
ans+="%20";
}
return ans;
}
};