Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a line in C/C++ using whitespace as delimiter [duplicate]

Tags:

c++

c

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?

like image 425
andandandand Avatar asked Nov 12 '10 23:11

andandandand


People also ask

How do you separate by whitespace?

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.

How split a string by space in C #?

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.

Can I split a string in C?

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.

How do you split a line by space in C++?

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.


3 Answers

Use strtok with " " as your delimiter.

like image 136
Donnie Avatar answered Nov 03 '22 02:11

Donnie


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).

like image 33
Steve Townsend Avatar answered Nov 03 '22 02:11

Steve Townsend


The easiest method is boost::split:

std::vector<std::string> words;
boost::split(words, your_string, boost::is_space());
like image 39
Inverse Avatar answered Nov 03 '22 01:11

Inverse