Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into tokens and save them in an array

Tags:

c

split

strtok

How to split a string into an tokens and then save them in an array?

Specifically, I have a string "abc/qwe/jkh". I want to separate "/", and then save the tokens into an array.

Output will be such that

array[0] = "abc" array[1] = "qwe" array[2] = "jkh" 

please help me

like image 287
Syeda Amna Ahmed Avatar asked Mar 18 '13 08:03

Syeda Amna Ahmed


People also ask

How do I split a string into an array of strings?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split a string and store it in an array 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.

How do you store tokens in an array?

You can represent a space (one or more) as a simple regular expression "\s+" and use a regex token iterator to iterate through the tokens, you can store the tokens in a vector from there.. Here is an example that just prints out the tokens. Using regular expressions for a simple substring search is an outright crime.


2 Answers

#include <stdio.h> #include <string.h>  int main () {     char buf[] ="abc/qwe/ccd";     int i = 0;     char *p = strtok (buf, "/");     char *array[3];      while (p != NULL)     {         array[i++] = p;         p = strtok (NULL, "/");     }      for (i = 0; i < 3; ++i)          printf("%s\n", array[i]);      return 0; } 
like image 72
rlib Avatar answered Sep 24 '22 17:09

rlib


You can use strtok()

char string[] = "abc/qwe/jkh"; char *array[10]; int i = 0;  array[i] = strtok(string, "/");  while(array[i] != NULL)    array[++i] = strtok(NULL, "/"); 
like image 25
MOHAMED Avatar answered Sep 21 '22 17:09

MOHAMED