在字符串的每个元素(不使用弦乐)的每个元素之后插入字符
Inserting character after every nth element of a string (not using stringstream)
我编写了一个函数,可以从字符串中删除空格和破折号。然后,它在每个第三个字符后插入一个空间。我的问题是,任何人都可以建议一种不使用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--] = ' ';
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;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 我有一个嵌套数组,它由另一个数组中的元素组成,这些元素分组为2.之后,我想显示每个元素的属性
- 在字符串的每个元素(不使用弦乐)的每个元素之后插入字符
- 为什么要指向数组或向量中最后一个元素之后的内存位置
- 矢量元素如何在矢量 std::move 之后保留其原始地址
- 在x元素之后,从QT中删除x元素之后的文件夹中的项目
- 如何在迭代器位置之后插入元素
- 如何有效地在元素之前和之后搜索关键短语
- 在链表中的specifeec元素之后添加元素,并删除第一个元素
- 从向量中移除元素,而不移除之后的元素
- Min-HeapSort在~350个元素之后不排序
- 在从循环中动态获得的值之后向数组中添加一个元素
- 为什么我指向 std::vector 元素的指针在 push_back() 之后更改了其值?
- 我应该在知道我将使用多少个元素之前还是之后定义向量中的元素数?
- C++在.size()之后丢失向量元素
- 在声明数组之后,所有元素都以某种方式成为最后一个元素
- 为什么在编组之后,数组中只有一个元素包含值