0

I want to split a string into an array of strings and I need to split them whenever a ',' is encountered.

In Java, we can use:-

String[] splitArray = input.split(",");

Is there any such a feature in C++ or I'll have to stick with the traditional way of doing this using a loop?

The solutions provided at a similar Ques. at StackOverflow Do not work for any delimiter other than space.

Vatsal Prakash
  • 558
  • 6
  • 17

1 Answers1

-3

strtok() does what you want: http://www.cplusplus.com/reference/cstring/strtok/

From the example:

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
    char str[] ="- This, a sample string.";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str," ,.-");
    while (pch != NULL)
    {
        printf ("%s\n",pch);
        pch = strtok (NULL, " ,.-");
    }

return 0;

}

Lee
  • 118
  • 11
  • 1
    This works for C prgramming, but in my case I've used #include ,rather than #include/#include and it takes String as string name="My name"; The above mentioned function won't work here. – Vatsal Prakash Jun 09 '16 at 17:09
  • 1
    All you have done is provide a plagiarized C answer to a C++ question. This is not a good answer IMHO. – NathanOliver Jun 09 '16 at 17:10
  • It works fine with ? What exactly is your problem when you say the function won't work? It's completely valid C++ code and works fine here. – Lee Jun 09 '16 at 17:14
  • 1
    Just because It can compile in C++ does not mean it is C++. If it compiles in a C compiler then it is C code not C++ code. – NathanOliver Jun 09 '16 at 17:15
  • strtok is a function defined in string.h .. it won't work if I've used #include – Vatsal Prakash Jun 09 '16 at 17:24