按C++的相反顺序拆分字符串
Split a string in reverse order C++
[编辑]我想写一个函数,以相反的顺序拆分给定的字符串,并将其存储在字符串数组中,类似于:
string* splitStr(string s, char c,int& ssize) {
int size = s.size();
string* ss = new string[size];
int count = 0;
ssize = 0;
for (int j = 0; j < size; j++) {
if (s.at(j) == c) {
count++;
}
}
ssize = ++count;
for (int i = 0; i<size; i++) {
if (s.at(i) == c) { ssize--; continue; }
else { ss[ssize] += s.at(i); }
}
ssize = count;
return ss;
}
示例程序:
string s = "this is some damn";
int size = 0;
string* ss = splitStr(s, ' ', size);
for (int i = 0; i < size; i++) {
cout << ss[i] << "n";
}
system("PAUSE");
输出:
(this is empty line)
damn
some
is
这只是一个粗略的尝试,但总的来说,这是一种非常不可靠的方法,你不认为吗?在这种情况下,最好的解决方案是什么,而不使用除string、char、int、float之外的任何其他数据类型?
基于解决方案的提升http://www.boost.org/doc/libs/1_61_0/doc/html/string_algo/usage.html#idp398633360和反向迭代器http://en.cppreference.com/w/cpp/container/vector
#include <iostream>
#include<boost/algorithm/string.hpp>
#include <vector>
int main()
{
std::string const str{"bla=blub"};
std::vector<std::string> elems;
boost::split(elems, str, boost::is_any_of("="));
for(auto const& elem : elems )
std::cout << elem << "n";
for(auto it=elems.rbegin(); it!=elems.rend(); ++it)
std::cout << *it << "n";
return 0;
}
阅读Kernighan和Ritchie
#include <string.h>
void reverse(char s[])
{
int length = strlen(s) ;
int c, i, j;
for (i = 0, j = length - 1; i < j; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
#include <stdio.h>
void strrev(char *p)
{
char *q = p;
while (q && *q) ++q;
for (--q; p < q; ++p, --q)
*p = *p ^ *q,
*q = *p ^ *q,
*p = *p ^ *q;
}
int main(int argc, char **argv)
{
do {
printf("%s ", argv[argc - 1]);
strrev(argv[argc - 1]);
printf("%sn", argv[argc - 1]);
} while (--argc);
return 0;
}
这就是XOR交换。请注意,您必须避免与self交换,因为a^a==0
。
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 函数调用中参数的顺序重要吗
- 为什么不;名字在地图上是按顺序排列的吗
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 数到第n个楼梯的路(顺序无关紧要)
- 优先顺序:智能指针和类析构函数
- 在循环中按顺序遍历成员变量
- 独立读取-修改-写入顺序
- C++将向量的向量拆分为向量的N个子向量
- QML按钮点击功能执行顺序
- C++中数据类型修饰符的顺序
- 当比特(而不是字节)的顺序至关重要时的持久性
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 通过选项卡的文本设置QTabWidget顺序
- c++11评估顺序(未定义的行为)
- 如何在C++中递归地按相反顺序打印集合
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- 给定顺序中的事件处理
- 具有包含其他对象的类的对象创建顺序
- 按C++的相反顺序拆分字符串