Extract substrings in C

I have a line: "foo$bar@baz"

I want to write a C program that will add all three substrings ( "foo", "bar"and "baz") and put them in its own line.

PS Donโ€™t worry, this is not homework .

+5
source share
4 answers

What you are looking for is strtok . It also allows the installation of dividers.

+10
source

if this is not for homework :-) than strtok is not recommended, if you can not use C ++ (why?), you should use strtok_r (version for the renderer)

+1
source

C, , . , ('\ 0') :

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

int main(int argc, char **argv) {

char *s1,*s2,*s3, *test = "foo$bar@baz";
char *buf=(char *)malloc(100);
char *p,c;

strcpy(buf, test);

s1 = p = buf;
while(c = *p) {
  if (c == '$') { *p = '\0'; s2 = p+1; }
  if (c == '@') { *p = '\0'; s3 = p+1; }
  p++;
}

printf("s1 = %s\n",s1);
printf("s2 = %s\n",s2);
printf("s3 = %s\n",s3);

}

, . , , , .

+1

Strtok , , , NULL, , . .

strsep, strtok, , , . .

, , , .

EDIT: this is not std c, so make sure you have this function before trying to use it. I know for sure that it is available in BSD and possibly in other versions of unix

EDIT: strsep and strtok_r seem to have the same functionality

0
source

All Articles