Remove spaces from std::string in C++

后端 未结 17 1414
说谎
说谎 2020-11-22 16:47

What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way?

相关标签:
17条回答
  • 2020-11-22 17:21
    string removeSpaces(string word) {
        string newWord;
        for (int i = 0; i < word.length(); i++) {
            if (word[i] != ' ') {
                newWord += word[i];
            }
        }
    
        return newWord;
    }
    

    This code basically takes a string and iterates through every character in it. It then checks whether that string is a white space, if it isn't then the character is added to a new string.

    0 讨论(0)
  • 2020-11-22 17:24
    std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
    str.erase(end_pos, str.end());
    
    0 讨论(0)
  • 2020-11-22 17:24

    Can you use Boost String Algo? http://www.boost.org/doc/libs/1_35_0/doc/html/string_algo/usage.html#id1290573

    erase_all(str, " "); 
    
    0 讨论(0)
  • 2020-11-22 17:24
      string str = "2C F4 32 3C B9 DE";
      str.erase(remove(str.begin(),str.end(),' '),str.end());
      cout << str << endl;
    

    output: 2CF4323CB9DE

    0 讨论(0)
  • 2020-11-22 17:25
    string replaceinString(std::string str, std::string tofind, std::string toreplace)
    {
            size_t position = 0;
            for ( position = str.find(tofind); position != std::string::npos; position = str.find(tofind,position) )
            {
                    str.replace(position ,1, toreplace);
            }
            return(str);
    }
    

    use it:

    string replace = replaceinString(thisstring, " ", "%20");
    string replace2 = replaceinString(thisstring, " ", "-");
    string replace3 = replaceinString(thisstring, " ", "+");
    
    0 讨论(0)
  • 2020-11-22 17:28

    Hi, you can do something like that. This function deletes all spaces.

    string delSpaces(string &str) 
    {
       str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
       return str;
    }
    

    I made another function, that deletes all unnecessary spaces.

    string delUnnecessary(string &str)
    {
        int size = str.length();
        for(int j = 0; j<=size; j++)
        {
            for(int i = 0; i <=j; i++)
            {
                if(str[i] == ' ' && str[i+1] == ' ')
                {
                    str.erase(str.begin() + i);
                }
                else if(str[0]== ' ')
                {
                    str.erase(str.begin());
                }
                else if(str[i] == '\0' && str[i-1]== ' ')
                {
                    str.erase(str.end() - 1);
                }
            }
        }
        return str;
    }
    
    0 讨论(0)
提交回复
热议问题