Question:
function to parse string in c?
2009-06-25 21:16:37 UTC
Hey, im trying to write a program that will take a string of words and spit them out one word at a time such as this:
hello world's
hello
world's

I wrote most of the program but I need help on getting started with teh function that will do the parsing. Can anyone get me started?


%%%%CODE%%%%
#include
#include
#define MAXLENGTH 256

char *next_word(char *instring, char **new_start);

int main()
{
char instring[MAXLENGTH];
char *words=NULL;
char *parsed=NULL;

printf("Enter the ******* text:\n");

fgets(instring, MAXLENGTH, stdin);

puts(instring);
words=next_word(instring, &parsed);

while (words != NULL)
{
printf("%s\n", words);
words=next_word(parsed, &parsed);
}
}

char *next_word(char *instring, char **new_start)
{

}
Three answers:
cja
2009-06-26 04:16:44 UTC
See below for a simple example of how to extract words. I like your idea of a next_word function. You should be able to use my logic to get that function working.



#include

#include



#define MAX_LINE_LEN 1024

#define WS " \",:;-(){}[]<>/\\=+\t"

#define END ".?!"



int main(int argc, char *argv[]) {

    FILE *fp;

    char line[MAX_LINE_LEN],*s;

   

    if ((argc < 2) ||

            ((fp = fopen(argv[1],"r")) == NULL)) {

        printf("\nusage : %s \n",argv[0]);

        return -1;

    }

    while (fgets(line,MAX_LINE_LEN,fp) != NULL) {

        *strchr(line,'\n') = '\0';

        for (s = strtok(line,WS);

                  s != NULL;

                  s = strtok(NULL,WS),strpbrk(s,END)) {

            printf("%s\n",s);

        }

    }

    puts("");

    fclose(fp);

    return 0;

}



Sample run:



$ ./words words.txt

Kenny

Perry

shot

a

61

to

tie

the

course

record

and

take

a

two

shot

lead

after

the

first

round

of

the

Travelers

Championship

on

Thursday.





Where:



$ cat words.txt

Kenny Perry shot a 61 to tie the course

record and take a two-shot lead after the

first round of the Travelers Championship

on Thursday.
Shaggy
2009-06-26 00:27:06 UTC
http://msdn.microsoft.com/en-us/library/ms228388(VS.80).aspx
Travis
2009-06-25 21:22:35 UTC
No. Do your own homework, scrub.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...