My problem solving
1. Traverse the string and determine whether it is a space character by character
class Solution {
public:
string replaceSpace(string s) {
if(s.empty()) return "";
string res;
for(int i=0;s[i];i++){
if(s[i]!=' ') res.push_back(s[i]);
else res+="%20";
}
return res;
}
};
2.for (auto c: s) It turns out that the for loop can be written like this, which is a bit comfortable
class Solution {
public:
string replaceSpace(string s) {
if(s.empty()) return "";
string res;
for(auto c : s){
if(c!=' ') res+=c;
else res+="%20";
}
return res;
}
};