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

时间:2016-08-29 12:26:44

标签: c++ string

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

 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之外的任何其他数据类型?

3 个答案:

答案 0 :(得分:0)

基于提升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;
}

答案 1 :(得分: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;
  }
}

答案 2 :(得分:-2)

 #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;
 }

这是XOR交换的事情。请注意,您必须避免与自己交换,因为a^a==0