【发布时间】:2018-09-11 14:19:31
【问题描述】:
我编写了一个函数,可以从字符串中删除空格和破折号。然后它在每 3 个字符后插入一个空格。我的问题是有人可以提出不使用stringstream 的不同方法吗?
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
using namespace std;
string FormatString(string S) {
/*Count spaces and dashes*/
auto newEnd = remove_if(S.begin(), S.end(), [](char c){return c == ' ' || c == '-';});
S.erase(newEnd, S.end());
std::stringstream ss;
ss << S[0];
for (unsigned int i = 1; i < S.size(); i++) {
if (i%3==0) {ss << ' ';}
ss << S[i];
}
return ss.str();
}
int main() {
std::string testString("AA BB--- ash jutf-4499--5");
std::string result = FormatString(testString);
cout << result << endl;
return 0;
}
【问题讨论】:
-
为什么?使用
std::stringstream有什么问题? -
@Someprogrammerdude 我只是好奇是否有另一种方法可以只使用迭代器和
std::string::insert?我想不通?谢谢 -
还有其他方法可以做到这一点,但它们更复杂且容易出错。使用输入字符串流或
std::string::insert既简单又直接。保持简单。
标签: c++ string stl iterator stringstream