Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extracting substrings in C

Tags:

c

string

I have the string: "foo$bar@baz"

I'm looking to write a C program which will extra all three sub-strings ("foo", "bar" and "baz") and put each into it's own string.

P.S. Don't worry, this is not homework.

like image 736
Jenna Avatar asked Dec 07 '09 18:12

Jenna


3 Answers

What you are looking for is strtok. It allows for you to set the delimiters as well.

like image 73
monksy Avatar answered Nov 16 '22 10:11

monksy


if it is not for homework :-) than strtok is not recommended, if you can't use C++ (why?) you should use strtok_r (reentrent version)

like image 37
Yuval Avatar answered Nov 16 '22 09:11

Yuval


Since this is straight C, it might be fun to revisit how strings are stored and terminated. Since you have one terminating character for each section, you can just make it into a true terminator ('\0') and leave the strings in place:

#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);

}

I wouldn't do this in production code, in this day and age. But way back when, doing one pass on the loop, and one copy for storage, would have been considered a big win.

like image 38
john personna Avatar answered Nov 16 '22 08:11

john personna