C++ 按C+的相反顺序拆分字符串+;
[编辑] 我想编写一个函数,将给定字符串按相反顺序拆分并存储在字符串数组中,类似于:C++ 按C+的相反顺序拆分字符串+;,c++,string,C++,String,[编辑] 我想编写一个函数,将给定字符串按相反顺序拆分并存储在字符串数组中,类似于: 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
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;
}
这只是一个粗略的尝试,但总的来说,这是非常不可靠的方法,你不觉得吗?在这种情况下,最好的解决方案是不使用除字符串、字符、int、float之外的任何其他数据类型。\include
#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("%s\n", argv[argc - 1]);
} while (--argc);
return 0;
}
无效strrev(字符*p)
{
char*q=p;
而(q&&*q)++q;
对于(--q;p
这是异或交换。请注意,您必须避免与self交换,因为a^a==0
基于boost和reverse迭代器的解决方案
#包括
#包括
#包括
int main()
{
字符串常量str{“bla=blub”};
std::向量元素;
boost::split(元素、str、boost::是(“=”)的任意元素);
用于(自动常量和元素:元素)
std::读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;
}
}
#包括
无效反向(字符s[])
{
整数长度=strlen(s);
int c,i,j;
对于(i=0,j=length-1;i 无所不在的行为。不能返回指向本地缓冲区的指针。您能提供示例输入和期望输出吗?看看升压分割,这不是C++:C++不允许返回数组和语法<代码>字符串[]
因为返回类型是非法的。也没有可以放在堆栈上的动态大小的内置数组。请不要使用xor交换,它只会使所有内容a)更难读取;b)更慢
#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("%s\n", argv[argc - 1]);
} while (--argc);
return 0;
}
#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;
}
#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;
}
}