Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string to 2 strings in C

Tags:

c

string

strtok

I was wondering how you could take 1 string, split it into 2 with a delimiter, such as space, and assign the 2 parts to 2 separate strings. I've tried using strtok() but to no avail.

like image 845
Mark Szymanski Avatar asked Mar 26 '10 13:03

Mark Szymanski


People also ask

How do I split a string into multiple strings?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.

What is strtok function in C?

The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.


2 Answers

#include <string.h>  char *token; char line[] = "SEVERAL WORDS"; char *search = " ";   // Token will point to "SEVERAL". token = strtok(line, search);   // Token will point to "WORDS". token = strtok(NULL, search); 

Update

Note that on some operating systems, strtok man page mentions:

This interface is obsoleted by strsep(3).

An example with strsep is shown below:

char* token; char* string; char* tofree;  string = strdup("abc,def,ghi");  if (string != NULL) {    tofree = string;    while ((token = strsep(&string, ",")) != NULL)   {     printf("%s\n", token);   }    free(tofree); } 
like image 120
ereOn Avatar answered Sep 23 '22 00:09

ereOn


For purposes such as this, I tend to use strtok_r() instead of strtok().

For example ...

int main (void) { char str[128]; char *ptr;  strcpy (str, "123456 789asdf"); strtok_r (str, " ", &ptr);  printf ("'%s'  '%s'\n", str, ptr); return 0; } 

This will output ...

'123456' '789asdf'

If more delimiters are needed, then loop.

Hope this helps.

like image 39
Sparky Avatar answered Sep 20 '22 00:09

Sparky