在字符串的每个第 n 个元素之后插入字符(不使用 stringstream)
Inserting character after every nth element of a string (not using stringstream)
我编写了一个从字符串中删除 space 和破折号的函数。然后它在每第 3 个字符后插入一个 space。我的问题是有人可以建议一种不使用 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;
}
如何使用输入字符串作为输出:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string FormatString(string S) {
auto newEnd = remove_if(S.begin(), S.end(), [](char c){return c == ' ' || c == '-';});
S.erase(newEnd, S.end());
auto str_sz = S.length();
/* length + ceil(length/3) */
auto ret_length = str_sz + 1 + ((str_sz - 1) / 3);
S.resize(ret_length);
unsigned int p = S.size()-1;
S[p--] = '[=10=]';
for (unsigned int i = str_sz-1; i>0; i--) {
S[p--] = S[i];
if (i%3 == 0)
S[p--] = ' ';
}
return S;
}
int main() {
std::string testString("AA BB--- ash jutf-4499--5");
std::string result = FormatString(testString);
cout << result << endl;
// AAB Bas hju tf4 499 5
return 0;
}
我编写了一个从字符串中删除 space 和破折号的函数。然后它在每第 3 个字符后插入一个 space。我的问题是有人可以建议一种不使用 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;
}
如何使用输入字符串作为输出:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string FormatString(string S) {
auto newEnd = remove_if(S.begin(), S.end(), [](char c){return c == ' ' || c == '-';});
S.erase(newEnd, S.end());
auto str_sz = S.length();
/* length + ceil(length/3) */
auto ret_length = str_sz + 1 + ((str_sz - 1) / 3);
S.resize(ret_length);
unsigned int p = S.size()-1;
S[p--] = '[=10=]';
for (unsigned int i = str_sz-1; i>0; i--) {
S[p--] = S[i];
if (i%3 == 0)
S[p--] = ' ';
}
return S;
}
int main() {
std::string testString("AA BB--- ash jutf-4499--5");
std::string result = FormatString(testString);
cout << result << endl;
// AAB Bas hju tf4 499 5
return 0;
}