tags:

views:

129

answers:

3

Possible Duplicate:
How to split a string?

Hi,

I have a string say "1,0,1", how can i get the substring separated by comma operator.

A: 

Search google for an algorithm to explode or tokenize your string. It's trivial.

You can also check out the documentation and use available tools : http://www.cplusplus.com/reference/string/string/

A simple implementation could be :

void tokenize(const string & text, vector<string> & tokens, char delim)
{
  size_t length = text.size();
  string token = "";

  for(size_t i=0;i<length;i++)
  {
      if(text[i] != delim)
      {
        token += text[i];
      }
      else
      {
        if(token.size() > 0)
        {
          tokens.push_back(token);
        }
        token = "";
      }
  }
  tokens.push_back(token);
}
Guillaume Lebourgeois
Since when did we start upvoting answers which say "search Google", or that the answer is "trivial" without actually *providing* an answer? -1 to compensate
jalf
It is absolutely useless to provide complete answers for this kind of question : if you _do_ want to help people, let them learn how to search for information, check out documentation and think by themselves. Offering complete answers just lead people to learn nothing at all.
Guillaume Lebourgeois
@jalf Since when did we start downvoting right answers ? Not voting is enough. His answer his right, pointing words to search on google for beginners. He doesn't give a complete answer since it would not be useful for a question like that. +1 to compensate jalf.
Scharron
jalf
@Guillaume: SO policy in general is that "RTFM" or "Let me Google it for you" type answers are **not** encouraged. SO is supposed to be where people can find reliable and trustworthy answers to their programming questions. If you Google for a tokenize algorithm, how do you know that the result you find is any good? There is a lot of crap programming advice on Google. **That is why SO was created**: when people Google for "tokenize algorithm", the #1 result should be a SO answer explaining it.
jalf
Here's what Joel and Jeff have to say on the subject, from http://blog.stackoverflow.com/2009/05/podcast-53/: "no question is too simple for Stack Overflow, and we discourage people from responding with RTFM or “too trivial to even ask”. These questions may be simple, but think about each question in terms of future programmers who might encounter this question; is it relevant enough to the world to help them, and not just the one guy or gal with that one ultra-narrow question? If so, then it’s worth asking."
jalf
@jalf From my point of view, the link pointing to cplusplus should be enough. The answer lacks a pointer of what to search in it, but it should be enough. The google part of the answer is not needed, but does not need a downvote. BTW, did you answer his question ?
Scharron
@Scharron: cplusplus.com contains *a lot* of crap. Going there doesn't ensure you get a *good* answer. (all it gives you is a list of string member functions, which isn't what the OP asked for). And yes, I did. It tookme some 10-15 minutes to write and test it (that's how "trivial" it is), hence the delay.
jalf
I sure understand your whish to follow SO policy, I didn't know this aspect of it. But it's in fact quite sad : I don't think it's stupid to ask simple questions, but I'd really prefer the person to think about the problem, and have a code proposal : then I'd be glad to help him improve it. Doing your way, anyone can ask a stupid question, don't think about it, and just copy and paste your answer somewhere without understanding a single word... and then come back here again asking simple questions instead of starting helping peoples. Your intentions are good, but short view.
Guillaume Lebourgeois
You're right, the asker should when possible have some source code themselves (that's in the FAQ too). But telling people to search Google doesn't really help them much. A complete beginner needs more than that. And searching Google has a good chance of either 1. landing you back here at SO, or 2. getting bad information. So what I try to do is provide answers that are more than just "here's the code you can copy/paste without thinking". I try to explain what/how/why as well.
jalf
I try to write answers that help the reader learn and understand. But if someone don't want to learn, it's their problem, not mine. Dozens of people might read even a low-traffic answer on SO. If just one of them actually understands the answer, it has served its purpose. Even if 30 others just copy/pasted it blindly, it means I helped one programmer improve himself.
jalf
+2  A: 

C++ doesn't have a built in function for doing exactly this. However, it can be implemented using either the std::string::find_first_of member function, or the non-member std::find.

Here's an example using the latter:

#include <string>
#include <vector>
#include <algorithm>


// given a string str, split it on every occurrence of the character delim
std::vector<std::string> tokenize(std::string str, char delim) {
    // store the results in a vector of strings
    std::vector<std::string> tokens;

    std::string::iterator end = str.end();
    std::string::iterator left = str.begin();
    for (;;) {
        // find the next occurrence of the delimiter
        std::string::iterator right = std::find(left, end, delim);
        // create a string from the end of last one up until the one we just foun
        tokens.push_back(std::string(left, right));
        // if we reached the end of the string, exit the loop
        if (right == end) { break; }
        // otherwise, start the next iteration just past the delimiter we just found
        left = right + 1;
    }
    return tokens;
}

// test program
int main() {
    std::string str = "foo, bar, baz";
    std::string str2 = "foo, bar, baz,";
    std::string str3 = "foo";
    std::string str4 = "";
    std::string str5 = ",";

    std::vector<std::string> tokens = tokenize(str, ',');
    std::vector<std::string> tokens2 = tokenize(str2, ',');
    std::vector<std::string> tokens3 = tokenize(str3, ',');
    std::vector<std::string> tokens4 = tokenize(str4, ',');
    std::vector<std::string> tokens5 = tokenize(str5, ',');
}

Of course there are a lot of border cases to handle, and this implementation might not do exactly what you want, but it should give you a starting point.

jalf
Returning a vector is not a great idea, it'd better be a function argument passed by reference.
Guillaume Lebourgeois
`find` is also available as a member function of `std::string`.
Scharron
@Guillaume: why? All major compilers implement NRVO even at low levels of optimization.
jalf
Sweet, revenge downvotes.. Yeah, that'll make me regret I dared to call out a crappy answer. If you think this answer deserves a downvote, how about explaining why?
jalf
Don't be silly, I was just looking around about NRVO. But it seems I can't undo the downvote now, my apologies. Let's say it's about the indentation then, I'd prefer GNU style ;) Anyway it finally seems to be a duplicate.
Guillaume Lebourgeois
A: 

another way of doing this is by using strtok. This is a old c way but it still applies to the problem.

using <vector>
using <string>

char* token, line[512];
std::string tokenStr;
std::string lineStr = "0, 1, 2";
std::vector<std::string> commaSplit;
strcpy ( line, lineStr.c_str());

//Remove spaces and find the first instance of ','
token = strtok( line, " ," );
while(token != NULL)
{
    //Copy the token to a string
    tokenStr = token;

    //Add the token to the vector
    commaSplit.push_back(token);

    //Find next instance of the ,
    token = strtok(NULL, " ,");
}
Wesley