c++ - 从字符串中删除多余的空格
问题描述
我遇到了一个有趣的练习。基本上我必须从字符串中删除所有多余的空格,过多的意思是字符串开头,字符串结尾的所有空格,并且不应有超过两个连续的空格。
这是我尝试过的
#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--;
}
}
谢谢大家帮助我。
解决方案
您可以利用std::stringstream
s 功能:
#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;
}
推荐阅读
- r - 如何在ggplot2中使用多色拟合线将颜色分配给多色散点图
- python - 选择 QTreeView 的最顶层项目
- flask - 石墨烯烧瓶返回空值
- ubuntu - Gradle:无法为 Linux amd64 加载本机库“libnative-platform.so”
- python - Matlab ode45和Scipy odeint之间的差异:相同的模型不同的结果
- spring-batch - 将一个 Spring Cloud Dataflow UI 用于多个批处理应用程序是否可行?
- python - 使用 SQLAlchemy MSSQL 连接时出现问题
- python - 如何构造矩阵形式的txt文件?
- python - 如何以 YAML 格式转储浮动值?
- reactjs - 在 React Native Expo 中使用 react-redux 更改另一个键的值