LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   tokenize to put in a char* argv[] list (https://www.linuxquestions.org/questions/programming-9/tokenize-to-put-in-a-char%2A-argv%5B%5D-list-594897/)

xeon123 10-26-2007 06:03 PM

tokenize to put in a char* argv[] list
 
Hi,

I would like to have a function that would produce the same content has the main(int argc, char* argv[] ) method produces.

I don't have a clue in how to do it. Can anybody give me a hint?
The main problem, is that I don't know how to tokenize a string that could have a variable number of spaces that separate each word:

For example:
Code:

[4spaces]ls[2 spaces]-la[10 spaces]>out.txt[7spaces]

or

ls>out.txt

and put this values inside a char* argv[].


Thanks,

xeon123 10-26-2007 06:06 PM

Or have another command like:
Code:

cat out.txt | sort

theNbomr 10-27-2007 12:13 PM

Code:

string0 = "This is    a    string  \n";
To convert it to a series of strings, simply scan along the string and at each transition from whitespace to non-whitespace save a pointer to the character at that position. At each opposite transition, replace the whitespace character at that position with a '\0' null terminator.

At the end, you will have accumulated an array of pointers, and the original string will now look like:

Code:

string0 = "This\0is\0  a\0  string\0  \n";
argv[0] ---^    ^      ^    ^   
argv[1] ---------+      |    |
argv[2] ----------------+    |
argv[3] ----------------------+
argc = 4;

Get a pointer to the start of the string, an array of char *'s in which to collect your string pointers, and a counter of strings found. A couple of temporary variables to remember state at each point along the original string will alow you to detect the transition states. Use the isspace() function to determine the class of character at each point along the string.

Hope this helps.
--- rod.

tronayne 10-28-2007 07:22 AM

This may do what you want; compile it, execute it, type a line of text and hit the return.
Code:

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

int    main    (void)
{
        char    buf [BUFSIZ];
        char    *tokptr, *strptr = buf;

        (void) gets (buf);
        while ((tokptr = strtok (strptr, " \t")) != (char *) NULL) {
                (void) fprintf (stdout, "%s\n", tokptr);
                strptr = (char *) NULL;
        }
        exit (EXIT_SUCCESS);
}



All times are GMT -5. The time now is 01:40 PM.