Re: [CODE] Char string manipulation

From: Daniel A. Koepke (
Date: 09/05/01

On Wed, 5 Sep 2001, Ragsdale, Jason D (Jason) wrote:
> In test_function I have a string that resembles this without the
> quotes "rank 1 leader,rank 2 coleader,rank 3 member" now this is in
> char *testbuf I need to be able to pull each item up to the comma into
> it's own array or buffer. So when I am done I would have buf1="rank 1
> leader" buf2="rank 2 coleader" and so fourth..... I hope this helps
> clarify my situation.

Perhaps instead of providing an example, you might be more clear if you
specify what you want to do in specific?  I'm clearly missing something if
my previous message was not enough to get you started.  If all of the
strings are of the format "rank <x> <y>" then you can do

  if (sscanf(buf, "rank %d %s,", &n, arg) == 2) {
     * We got "rank <x> <y>", n has the number <x> in it, arg has the word
     * "coleader" or "leader" etc.
  } else ... /* We got something else, do something with it. */

or, if you really just want to split at an arbitrary character:

  char *split_string(char *orig, char *word, char delim)
    while (isspace(*orig))

    for ( ; *orig && *orig != delim; orig++)
      *(word++) = *orig;

    *word = '\0';
    return (orig);

and then you can do:

  void test_function(char *testbuf)
    char buf1[MAX_INPUT_LENGTH];
    char buf2[MAX_INPUT_LENGTH];
    char buf3[MAX_INPUT_LENGTH];

    /* testbuf == "rank 1 leader, rank 2 coleader, rank 3 member" */
    testbuf = split_string(testbuf, buf1, ',');
    testbuf = split_string(testbuf, buf2, ',');
    testbuf = split_string(testbuf, buf3, ',');

     * buf1 == "rank 1 leader"
     * buf2 == "rank 2 coleader"
     * buf3 == "rank 3 member"

If you're parsing a file format, there are other ways to do things that
are perhaps better.  Most books on C will cover things like this.


   | FAQ: |
   | Archives: |

This archive was generated by hypermail 2b30 : 12/06/01 PST