Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by single spaces [duplicate]

Tags:

c++

string

Possible Duplicate:
How to split a string in C++?

I need to split a string by single spaces and store it into an array of strings. I can achieve this using a istringstream, but what I am not being able to achieve is this:

I want every space to terminate the current word. So, if there are two spaces consecutively, one element of my array should be blank.

For example:

(underscore denotes space)

This_is_a_string. gets split into: A[0] = This A[1] = is A[2] = a A[3] = string.  This__is_a_string. gets split into: A[0] = This A[1] = "" A[2] = is A[3] = a A[4] = string. 

How can I implement this?

like image 891
xbonez Avatar asked May 04 '11 18:05

xbonez


1 Answers

If strictly one space character is the delimiter, probably std::getline will be valid.
For example:

int main() {   using namespace std;   istringstream iss("This  is a string");   string s;   while ( getline( iss, s, ' ' ) ) {     printf( "`%s'\n", s.c_str() );   } } 
like image 50
Ise Wisteria Avatar answered Sep 19 '22 22:09

Ise Wisteria