Possible Duplicate:
How do I tokenize a string in C++?
pseudocode:
Attributes[] = Split line(' ')
How?
I have been doing this:
char *pch;
pch = strtok(line," ");
while(pch!=NULL)
{
fputs ( pch, stdout );
}
and getting a non-written, stuck, exit file. It's something wrong with this? Well, the thing isn't even meeting my pseudocode requirement, but I'm confused about how to index tokens (as char arrays) to my array, I guess I should write a 2-dim array?
You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.
To split a string we need delimiters - delimiters are characters which will be used to split the string. Suppose, we've the following string and we want to extract the individual words. char str[] = "strtok needs to be called several times to split a string"; The words are separated by space.
In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.
You can use string's find() and substr() methods to Split String by space in C++. This is more robust solution as this can be used for any delimeter.
Use strtok
with " "
as your delimiter.
This is not quite a dup - for C++ see and upvote the accepted answer here by @Zunino.
Basic code below but to see the full glorious elegance of the answer you are going to have to click on it.
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
int main() {
using namespace std;
string sentence = "Something in the way she moves...";
istringstream iss(sentence);
copy(istream_iterator<string>(iss),
istream_iterator<string>(),
ostream_iterator<string>(cout, "\n"));
}
This hinges on the fact that by default, istream_iterator
treats whitespace as its separator. The resulting tokens are written to cout
on separate lines (per separator specified in constructor overload for ostream_iterator).
The easiest method is boost::split
:
std::vector<std::string> words;
boost::split(words, your_string, boost::is_space());
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