1

I'm trying to find a way to convert a string to array of c strings. So for example my string would be:

std::string s = "This is a string."

and then I would like the output to be something like this:

array[0] = This
array[1] = is
array[2] = a
array[3] = string.
array[4] = NULL
Peter T.
  • 15
  • 1
  • 1
  • 4

3 Answers3

4

You are trying to split string into strings. Try:

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

 std::string s = "This is a string.";

  std::vector<std::string> array;
  std::stringstream ss(s);
  std::string tmp;
  while(std::getline(ss, tmp, ' '))
  {
    array.push_back(tmp);
  }

  for(auto it = array.begin(); it != array.end(); ++it)
  {
    std::cout << (*it) << std:: endl;
  }

Or see this split

Community
  • 1
  • 1
billz
  • 44,644
  • 9
  • 83
  • 100
1

Split your string into multiple strings based on a delimiter using the Boost library function 'split' like this:

#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of(" "));

And then iterate over the strs vector.

This approach allows you to specify as many delimiters as you like.

See here for more: http://www.boost.org/doc/libs/1_48_0/doc/html/string_algo/usage.html#id3115768

And there is a plethora of approaches here: Split a string in C++?

Community
  • 1
  • 1
HXCaine
  • 4,228
  • 3
  • 31
  • 36
-2

On your example.

The array is not an array of characters, it is an array of strings.

Well, actually, a string is an array of characters.

//Let's say:
string s = "This is a string.";
//Therefore:
s[0] = T
s[1] = h
s[2] = i
s[3] = s

But based on your example,

I think you want to Split the text. (with SPACE as delimeter).

You can use the Split function of the String.

string s = "This is a string.";
string[] words = s.Split(' ');
//Therefore:
words[0] = This
words[1] = is
words[2] = a
words[3] = string.
Arvie
  • 47
  • 4
  • 3
    You're going to have to divulge which **C++** standard dictates the `Split()` member of `std::string`. This isn't Java. – WhozCraig Feb 12 '13 at 01:24