Friday, May 3, 2019

C++: split a string into an array


#include <vector>
#include <string>
#include <iostream>

using namespace std;

int main() {
  string str = "aaa:bbbb:ccccc:dd:eee:ffff:ggggg";

  vector<string> array;

  const char* p = str.c_str();
  unsigned sz = str.size();
  char buf[sz];
  const char dt = ':';

  int pos = 0;
  for (int i = 0; i < sz; i++) {
    if (dt != *p) {
      buf[pos] = *p;
      pos++;
    }

    if (dt == *p ||
        i == sz - 1) {  // last char
      buf[pos] = '\0';
      array.push_back(buf);   // got one token
      pos = 0;      // point to the start of buf[]    
    }

    p++;   // next char
  }

  // print out the array
  for (int j = 0; j < array.size(); j++) {
    std::cout << array[j] << std::endl;
  }
}

No comments:

 
Get This <