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?
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() ); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With