问题
I'm trying to write a little program to reverse the words in a string (the classic interview question) but I'm hitting a bit of a snag. On another portion of the site, I came across a really cool way to reverse strings in place using bitwise operations, so I'm attempting to use a program that only utilizes a single reverse() that will be called in reverse the entire string and then the substrings.
Unfortunately, my program will only reverse the first substring and I'm having trouble finding out why. Any help would be much appreciated.
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
void reverse(char string[], int beg, int end) {
int length = end-beg-1;
for(int i=beg; i < length/2; i++) {
string[i] = string[i] ^string[length-i];
string[length-i] = string[i] ^ string[length - i];
string[i] = string[i] ^string[length-i];
}
}
int main (int argv, char * arrv[]) {
int beg, end;
char string[] = "This is the string to reverse";
int length = strlen(string);
printf("%s\n", string);
printf("%d\n", length);
//reverse whole string
reverse(string, 0, length);
printf("%s\n", string);
beg =0;
end = 0;
//reverse strings at index's beg and end
for(int i = 0; i <= length-1; i++) {
if (string[i] == ' ') {
reverse(string, beg, end);
beg = i+1;
}
end++;
printf("%s\n", string);
}
printf("%s\n", string);
return 1;
}
Thanks I.E Expected Output: reverse to string the is this My Output: reverse ot gnirts eht si siht
回答1:
Adding up @alexd 's suggestion, following is the updated program with few fixes:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
void reverse(char string[], int beg, int end) {
int length = end - beg;
for (int i = 0; i < length / 2; i++) {
string[beg + i] = string[beg + i] ^ string[end - 1 - i];
string[end - 1 - i] = string[beg + i] ^ string[end - 1 - i];
string[beg + i] = string[beg + i] ^ string[end - 1 - i];
}
}
int main (int argv, char * arrv[]) {
int beg, end;
char string[] = "This is the string to reverse";
int length = strlen(string);
printf("%s\n", string);
printf("%d\n", length);
//reverse whole string
reverse(string, 0, length);
printf("%s\n", string);
beg =0;
end = 0;
//reverse strings at index's beg and end
for(int i = 0; i <= length-1; i++) {
if (string[i] == ' ') {
reverse(string, beg, end);
beg = i+1;
printf("%s %d %d\n", string, beg, end);
} else if(i==length-1) {
end = length;
reverse(string, beg, end);
}
end++;
}
printf("%s\n", string);
return 1;
}
来源:https://stackoverflow.com/questions/29243374/having-trouble-writing-program-to-reverse-words-in-string-in-c