In: Computer Science
In this C program, the function reverseStr reverses the nth word in a string. If n is larger than the number of words in the string then the function returns 0, else return the function modifies the string and returns 1.
Task: write the reverseStr function that follow the requirements below:
1. consistent with the prototype and code below
2. original string must be changed
3. DON'T use functions in string.h
Tips:
1. string input to this function is non-empty, that includes one or more non-whitespace characters
2. every consecutive word in the string is separated by single space characters and has no punctuation marks
3. string always start with a non-whitespace character
4. string is always terminated with a null '\0' character
5. the value of n > 0
Please use this program:
#include <stdio.h>
int reverseStr(char *string, int n);
int main(void)
{
char input[] = "Pizza is much better than burger";
int n = 4;
printf("Original: %s\n", input);
printf("n = %d\n", n);
if (reverseStr(input, n))
{
printf("New: %s\n", input);
}
else
{
printf("Error!!!! Number of words in %s is less than %d\n", input, n);
}
return 0;
}
Expected Output:
Original: Pizza is much better than burger
n = 4
New: Pizza is much retteb than burger
Note: Please screenshot your output window
All the explanation is in the comments of the code itself.
Code--
#include <stdio.h>
int reverseStr(char *string, int n);
int main(void)
{
char input[] = "Pizza is much better than burger";
int n = 6;
printf("Original: %s\n", input);
printf("n = %d\n", n);
if (reverseStr(input, n))
{
printf("New: %s\n", input);
}
else
{
printf("Error!!!! Number of words in %s is less than %d\n", input,
n);
}
return 0;
}
int reverseStr(char *string, int n)
{
int word=1,i=0;
//reach the index on the nth word
while(word<n)
{
//if nth word does not exist return 0
if(string[i]=='\0')
{
return 0;
}
//if it is a space increase the
word by 1
if(string[i]==' ')
{
word++;
}
i++;
}
int end=i+1;
//reach the last letter of the word to be reversed
while(string[end]!=' ' )
{
if(string[end]=='\0')
break;
end++;
}
end--;
//reverse the word
while(i<end)
{
char temp=string[i];
string[i]=string[end];
string[end]=temp;
i++;
end--;
}
return 1;
}
Output Screenshot--
Note--
Please upvote if you like the effort.