How to split a C string by a string?

Unga unga888 at yahoo.com
Wed Sep 17 13:32:57 UTC 2008


--- On Wed, 9/17/08, Giorgos Keramidas <keramida at ceid.upatras.gr> wrote:

> From: Giorgos Keramidas <keramida at ceid.upatras.gr>
> Subject: Re: How to split a C string by a string?
> To: unga888 at yahoo.com
> Cc: freebsd-questions at freebsd.org
> Date: Wednesday, September 17, 2008, 6:17 PM
> On Wed, 17 Sep 2008 00:45:46 -0700 (PDT), Unga
> <unga888 at yahoo.com> wrote:
> > Hi all
> >
> > I'm writing an C application on FreeBSD 7+. I need
> to split a string
> > by another string (ie. the delimiter is
> "xxx") similar to strtok split
> > a string by a single char. Is there a standard
> function or is there a
> > FreeBSD functions for this?
> 
> You can use strstr() to look for the "xxx"
> delimited and split that that
> point:
> 
>   % cat -n foo.c
>        1  #include <stdio.h>
>        2  #include <string.h>
>        3
>        4  int
>        5  main(void)
>        6  {
>        7          char text[] = "Hello string
> world";
>        8          char delim[] = " string ";
>        9          size_t dlen = sizeof(delim) /
> sizeof(delim[0]) - 1;
>       10          char *p;
>       11
>       12          p = strstr(text, delim);
>       13          if (p == NULL)
>       14                  return 0;               /* No
> match */
>       15
>       16          printf("First part = 
> \"%.*s\"\n", p - text, text);
>       17          printf("Second part =
> \"%s\"\n", p + dlen);
>       18          return 0;
>       19  }
>   % cc -std=iso9899:1990 -O2 -Wall foo.c
>   % ./a.out
>   First part =  "Hello"
>   Second part = "world"
>   %

Thank you very much for the reply. That is, there is no existing split function. So I got to write to my own :)

Best regards
Unga


      


More information about the freebsd-questions mailing list