-
Reverse words in string
Hi, I have written a program to reverse words in a string. So if the input is: "My name is Jack", the output should be "yM eman si kcaJ".
But my program is not outputting anything.
Code:
#include <stdio.h>
#include <string.h>
int main(){
char str[100];
char temp[100];
int i, j, k;
int start = 0;
printf("Enter string:");
gets(str);
for (i = 0; i < strlen(str); i++){
if (str[i] == " "){
k = 0;
for (j = start; j < i; j++){
temp[k] = str[j];
k++;
}
temp[k] = '\0';
strrev(temp);
printf("%s", temp);
start = i + 1;
}
}
return 0;
}
Anyone know why my program is not outputting anything?
-
Well, one thing is that this line will never (or rather, is very unlikely to) evaluate to true:
since you're comparing a char to a string. Change it to:
and take it from there.
-
Thanks!
Thanks JohnGraham! That solves a big part of the problem.
But it is still not printing the reverse of the last word of the string. For example, when the input is "Hello how are you", the program outputs "olleH woh era". The last word is not reversed. Here's the code (which I have modified) again:
Code:
#include <stdio.h>
#include <string.h>
int main(){
char str[100];
char temp[100];
int i, j, k;
int start = 0;
printf("Enter string:");
gets(str);
for (i = 0; i < strlen(str); i++){
if (str[i] == ' ' || str[i] == '\0'){ /* modified this statement */
k = 0;
for (j = start; j < i; j++){
temp[k] = str[j];
k++;
}
temp[k] = '\0';
strrev(temp);
printf("%s ", temp);
start = i + 1;
}
}
return 0;
}
Anyone know why it is not reversing the last word?
-
Solved
Wait, my question is solved. The program now reverses the last word too. Here's the modified final code:
Code:
#include <stdio.h>
#include <string.h>
int main(){
char str[100];
char temp[100];
int i, j, k;
int start = 0;
printf("Enter string:");
gets(str);
for (i = 0; i <= strlen(str); i++){
if (str[i] == ' ' || str[i] == '\0'){
k = 0;
for (j = start; j < i; j++){
temp[k] = str[j];
k++;
}
temp[k] = '\0';
strrev(temp);
printf("%s ", temp);
start = i + 1;
}
}
return 0;
}