Thread: tokenize string to array of strings c

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    10

    tokenize string to array of strings c

    Hi,
    I've gotten pretty good at C but can't seem to logically or actually figure this out....


    I'm taking a string, it can be any string, and tokenizing it. This is the part of the code that matters. How do I save each token to a new string? There is an unknown amount of tokens.


    I know I could define X amount of strings but I want to do this dynamically.


    Code:
    tok = strtok(getenv("PATH"), ":");
    	printf("Tokens: \n");
    	
    	while (tok != NULL){
    		printf("%s\n", tok);
    		tok = strtok(NULL, ":");
    }
    Thanks!

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    First look up strtok() in your compiler's library documentation (don't have it? ... get it!)

    strtok() returns a pointer to the isolated string.
    All you have to do is save the pointers in an array.

    It also alters the string, so you probably don't want to use the getenv() command inside your first strtok call... it would be far better to copy it to a separate string than trying to operate on an environment variable directly. (Ask how badly you want to screw up your system...)
    Last edited by CommonTater; 12-06-2011 at 09:27 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to write a function to tokenize a string
    By anukta_c in forum C Programming
    Replies: 2
    Last Post: 08-21-2011, 02:53 PM
  2. tokenize a string
    By Whilst in forum C Programming
    Replies: 6
    Last Post: 10-20-2009, 09:00 PM
  3. how to break a string into array of strings
    By transgalactic2 in forum C Programming
    Replies: 34
    Last Post: 06-26-2009, 02:27 PM
  4. search numbers in an inputed string [array of strings]
    By zattara13 in forum C Programming
    Replies: 1
    Last Post: 03-28-2008, 06:11 AM
  5. Tokenize string from text file
    By young-ie in forum C Programming
    Replies: 6
    Last Post: 04-16-2007, 09:07 AM