Sword Finger Offer Interview Question 05. Replace spaces [Simple]-for (auto c: s)

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;
    }
};

Published 65 original articles · Like1 · Visits 485

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/105468207
Recommended