Sword refers to Offer05-replace spaces-easy

Question link

Title description:

Please implement a function to replace each space in the string s with "%20".

For example, enter:

输入:s = "We are happy."
输出:"We%20are%20happy."

data range:

0 <= s 的长度 <= 10000

Problem-solving ideas:

1. Create a string s1
2. Traverse s
when s[i] == space, s1 += "%20"
otherwise s1 += s[i]

AC code (c++)

class Solution {
    
    
public:
    string replaceSpace(string s) {
    
    
        string s1="";
        for(int i=0;i<s.size();i++){
    
    
            if(s[i]== ' '){
    
    
                s1+="%20";
            }else{
    
    
                s1 += s[i];
            }
        }
        return s1;
    }
};

Guess you like

Origin blog.csdn.net/Yang_1998/article/details/113047622
Recommended