Write a program that inputs a line of text, tokenizes the line with function str
ID: 3762714 • Letter: W
Question
Write a program that inputs a line of text, tokenizes the line with function strtok and outputs the tokens in reverse order. (C Code)
Here is what I have so far.
#include <stdio.h>
#include <string.h>
#define SIZE 80
int main (void)
{
// initialize array string
char string[SIZE];
char *reversestring[SIZE];
char *tokenPtr; // create char pointer
int count = 1;
printf("Enter a line of text to be tokenized and reversed. ");
fgets( string, SIZE, stdin );
printf("%s %s %s ",
"The string to be tokenized is:", string,
"The tokens are:" );
tokenPtr = strtok( string, " " ); // begin tokenizing sentence
reversestring[0] = *tokenPtr;
// continue tokenizing sentence until tokenPtr becomes NULL
while ( tokenPtr != NULL ) {
printf( "%s ", tokenPtr );
tokenPtr = strtok( NULL, " " ); // get next token
reversestring[count] = *tokenPtr;
count++;
} // end while
while(count!=0) {
printf("%s ", reversestring[count]);
count--;
}
} // end main
----------------------------
The OUTPUT looks like this.
Enter a line of text to be tokenized and reversed.
my name is
The string to be tokenized is:
my name is
The tokens are:
my
name
is
(null)
(null)
is
name
logout
Explanation / Answer
#include <stdio.h>
#include <string.h>
int main()
{
char line[30] = "i want to c this is revers";
char *tokens[30];
int max_tokens = sizeof(tokens)/sizeof(tokens[0]);
char *token_ptr;
int k;
printf("Original line of text: <%s> ", line);
token_ptr = strtok(line, " ");
for (k = 0; k < max_tokens && token_ptr != NULL; k++)
{
tokens[k] = token_ptr;
printf("tokens[%d]: <%s> ", k, tokens[k]);
token_ptr = strtok(NULL, " ");
}
printf("Number of tokens = %d ", k);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.