首页 > 解决方案 > 从字符串中删除多余的空格

问题描述

我遇到了一个有趣的练习。基本上我必须从字符串中删除所有多余的空格,过多的意思是字符串开头,字符串结尾的所有空格,并且不应有超过两个连续的空格。

这是我尝试过的

#include <iostream>
#include <string>
using namespace std;

string RemoveSpaces(string s) {
    auto it = s.begin();
    while(*it == ' ') { // removes spaces at the beginning
        if(*it == ' ') s.erase(it);
    }

    auto it2 = s.end(); // removes spaces at the end of a string
    it2--;

    while(*it2 == ' ') it2--;
    it2++;
    while(*it2 == ' ') {
        if(*it2 == ' ') s.erase(it2);
    }

    for(int i = 0; i < s.length() - 1; i++) { // this does NOT work
        if(s.at(i) == ' ' && s.at(i + 1) == ' ') {
            auto it3 = s.at(i);
            s.erase(it3);
        }
    }

    return s;
}

int main() {
    string s;
    getline(cin, s);

    string s1 = RemoveSpaces(s);

    cout << "|" << s << "|" << endl;
    cout << "|" << s1 << "|" << endl;

    return 0;
}


但是,这并没有达到我的预期。我的代码成功地删除了字符串开头和结尾的空格,但我不能走得更远。任何人都可以帮忙吗?

编辑我解决了这个问题。这是现在删除单词之间多余空格的代码部分,以便在两个单词之间只留下一个空格。

    auto it3= s.begin();

    for(int i = 0; i < s.length() - 1; i++) {
        if(s.at(i) == ' ' && s.at(i + 1) == ' ') {
            s.erase(s.begin()+i);
            i--;
        }

    }

谢谢大家帮助我。

标签: c++

解决方案


您可以利用std::stringstreams 功能:

#include <string>
#include <sstream>

std::string RemoveSpaces(const std::string& str) {
    std::string out;                 // the result
    std::string word;                // used to extract words from str 
    std::istringstream ss(str);      // create an istringstream from str
    while(ss >> word) {              // extract a word
        if(!out.empty()) out += ' '; // add a space between words
        out += word;                 // add the extracted word 
    }
    return out;
}

推荐阅读