1

I have this string: "apples,cakes,cupcakes,bannanas"

How can I efficiently break this up into an array like the following?

["apples"]["cakes"]["cupcakes"]["bannanas"]

There seem to be a lot of answers for c++ out there but I am struggling to find a answer for C. All i want to do is split this into a array at every ','. Any suggestions??

4
  • The easy way is std::getline on an input stream. Read up on std::stringstream for a quick way to turn a string into an input stream. Commented Jan 20, 2016 at 4:59
  • I thought std was a c++ library. Sorry, I am new to c and c++. Commented Jan 20, 2016 at 5:01
  • 1
    You tagged the question with C++, I gave a C++ answer. If you need to restrict your answers to C, edit your question and replace the C++ tag with the C tag. You will probably get a better quality of response. Commented Jan 20, 2016 at 5:05
  • Sorry im coding with c++ but using c strings. Commented Jan 20, 2016 at 5:10

2 Answers 2

3

use strtok()?

string str as apples,cakes,cupcakes,bannanas and delim ",".

char *token;
token = strtok(str, delim);
while(token != NULL)
{
       printf("%s\n", token);
       token = strtok(NULL,delim);
 }

may this help.

Sign up to request clarification or add additional context in comments.

5 Comments

How does this return an array on strings??? I need a array with each split string in it.
Replace the print line with a strcpy of the char array into the string array. Or better still, use std::vector.
Thanks!! I just pushed the token into a vector :D
Two things to watch out for: 1. strtok destroys your source string. This is OK if you aren't using the string again and you aren't using it on a constant string with the assistance of a cast. 2. If you place the char * returned from strtok into the std::vector without copying the string at the char * into a char array in the std::vector, the std::vector relies on the continued existence of the tokenized string. If this string goes out of scope, all the pointers in the std::vector will refer to garbage and further use will result in unpredictable and undefined behaviour.
Too late to edit my previous comment. "strtok destroys your source string." is really bad wording. The string isn't destroyed in the destructor sense. The contents are changed. In this case every time strtok encounters a ',', the ',' is replaced with a null. Attempts to read from the source string will terminate at the end of the first token because it is now null terminated.
1

You have several options.

You can use strtok function See documentation for strtok here

Similar question was asked before here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.