0

How do I split a string with delimiter character 'space'?

My code:

string* splitstring(string StrToSplit) {
  string substr[100];
  int k = 0;
  for (int j = 0; j < StrToSplit.length(); j++) {
    if (StrToSplit[j] == ' ') {
      k++;
    } else {
      string chartostring(1, StrToSplit[j]);
      substr[k].append(chartostring);
      cout << substr[k] << endl;
    }
  }
  return substr;
}
  • Welcome to SO! You can do yourself and us a favour and make sure you provide a [mcve]. I took the liberty to edit your post and improve it somewhat, but you should still have a look yourself. – mindriot May 11 '16 at 10:15
  • I know it's marked as duplicate but there's another problem with your code - never return locally created array by a pointer, as it's gonna be long gone after the end of the function. Instead of `string substr[100]`, create it with `new` operator, like `string* substr = new string[100]`, or - even better - check out [std::vector](http://www.cplusplus.com/reference/vector/vector/). We can't be sure that array of size 100 will be enough to keep all of your strings after split, while `vector` has the ability to "resize" itself. – Bartłomiej Zieliński May 11 '16 at 10:17

0 Answers0