I have a string with the name "Mustang Sally Bob"
After i run my code i want the string output to be like this: gnatsuM yllaS boB
My approach is to count the words until the space and save the index of where the space is located in the string. then Then I want to print the characters starting from the space backwards.
#include <stdio.h>
int main()
{
char* test="Mustang Sally Bob";
int length; //string length
int x;
for(length=0;test[length] !=0&&test[length];length++); //get string length
int counter;
int words = 0;
int space_index =0;
for(counter=0;counter<length;counter++) {
words++;
if(test[counter]==' ') {
space_index=counter;
for(x=space_index-1;x>=words;x--) {
printf("%c",test[x]);
}
words=0;
space_index = 0;
}
}
return 0;
}
but when I execute this code the output I get is yllaS g
does anyone know why i cant get the full string?
In general the approach is incorrect.
For example an arbitrary string can start with blanks. In this case the leading blanks will not be outputted.
The last word is ignored if after it there is no blank.
The variable
words
does not keep the position where a word starts.Calculating the length of a string with this loop
that can be written simpler like
is redundant. You always can rely on the fact that strings are terminated by the zero-terminating character
'\0'
.I can suggest the following solution
The program output is
You could append the program with a check of the tab character
'\t'
if you like. In C there is the standard C functionisblank
that performs such a check.Here is a demonstrative program that uses the function
isblank
. I also changed the original string literal.The program output is