Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Strings Lab Exercise You are to write a program with two helper functions asdesc

ID: 3614709 • Letter: S

Question

Strings Lab Exercise

You are to write a program with two helper functions asdescribed below. Your program will prompt the user to input asentence, which you will input with the gets function (syntax:gets(str);). Your program will then print the sentence withthe order of the words reversed.

An example run of the program, with user input underlined:

Enter a sentence:   you can cage a swallowcan't you
Reversal of sentence: you can't swallow a cage canyou

You should provide two helper functions:

void replace_whitespace(char *str);
/* replaces every whitespace character in str with the null
   character; uses the function isspace(char c) fromctype.h */

int get_words(char *line, chartokens[MAX_WORDS][MAX_LEN+1]);
/* Goal: to store the words from string line in the array
         tokens, one wordper entry. */

Suggestion:

Have the function compute the length len of the string line,then call replace_whitespace(line).

Each separate word in the array line is now followed by one ormore null characters.   Next find the start of each wordin the array and use strcpy to enter the word in the array of tokenstrings (second parameter)

You can use either a pointer or index to find the firstletter of each word. If you pass a pointer to that characteras the second argument of strcpy, it will copy theword starting at that position, since it is nownull-terminated. You then have to skip over null characters tofind the start of the next word.

Warning: you must use a count of all characters traversed(both null characters and characters read into one of theentries in token) to make sure you do not go beyond the end of theoriginal string input into the array line.

Explanation / Answer

//here are twofunctions int get_words(char*line, char tokens[MAX_WORDS][MAX_LEN+1])
{
    int i,len;
    int count=0;
    for(i=0;i<MAX_LEN;i++)
    {
     if(line[i]!='')
      {
       len =strlen(&line[i]);
      strcpy(&tokens[count++][0],&line[i]);
       i=i+len;
      }
    }
    return count;
}


void replace_whitespace(char *str)
{
int i,len;
len = strlen(str);
for(i=0;i<len;i++)
if(isspace(str[i]))
str[i]='';

}