按C++的相反顺序拆分字符串

Split a string in reverse order C++

本文关键字:顺序 拆分 字符串 C++      更新时间:2023-10-16

[编辑]我想写一个函数,以相反的顺序拆分给定的字符串,并将其存储在字符串数组中,类似于:

 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