Remove spaces from std::string in C++

后端 未结 17 1640
说谎
说谎 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.

提交回复
热议问题