Knitex
Knitex

Reputation: 225

Splitting a string in C

I need to split a string in C. I know I can use strtok but I am not really sure how to use it.

For example, I want to split this: "L 90,120,130,140" and I want to get the 'L' and, then, the integers separated by the , (comma).

Upvotes: 0

Views: 240

Answers (5)

bspikol
bspikol

Reputation: 96

This is just a supplement to the other answers. Remember that strtok() is not reentrant. If you are in a thread, use strtok_r.

Upvotes: 0

hol
hol

Reputation: 8423

char str[]="L 90,120,130,140";
char *tok;
tok = strtok (str," ,");

while (tok != NULL) {
    if (isdigit(tok[0])) {
        int i = atoi(&tok[0]);
        printf("number %i\n",i);
    } else {
        printf("string %s\n",tok);            
    }
    tok = strtok(NULL," ,");
}

output:

string L
number 90
number 120
number 130
number 140

Can be further improved if floats are part of the string

Upvotes: 1

user411313
user411313

Reputation: 3990

strtok will destroy your string, you should use sscanf instead:

char s[2];
int a,b,c,d;
if( sscanf("L 90,120,130,140","%1s%d,%d,%d,%d",s,&a,&b,&c,&d)==5 )
  puts("reading was OK");

Upvotes: 0

January
January

Reputation: 17140

Here is a complete example:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  char str[]="L 90,120,130,140";
  char *p ;

  p = strtok( str, " " ) ; // p is now pointer to 'L\0'
  printf( "first token: %s\n", p ) ;

  while( p = strtok( NULL, "," ) ) printf( "next token: %s\n", p ) ;

  exit( 0 ) ;
}

Upvotes: 0

P.P
P.P

Reputation: 121427

Use multiple delimiters in your strtok:

  char str[]="L 90,120,130,140";
  char *tok;
  tok = strtok (str," ,");

Then loop through and store them as you want.

Upvotes: 2

Related Questions