gpt4 book ai didi

c - 在 C 中编写程序来反转字符串中的单词时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:37:54 26 4
gpt4 key购买 nike

我正在尝试编写一个小程序来反转字符串中的单词(经典面试问题),但遇到了一些障碍。在该网站的另一部分,我发现了一种非常酷的方法来使用按位运算来反转字符串,所以我尝试使用一个程序,它只使用一个 reverse() 来反转整个字符串,然后是子串。

不幸的是,我的程序只会反转第一个子字符串,我很难找出原因。任何帮助将不胜感激。

#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;
}

谢谢IE预期输出:反向字符串 the is this我的输出:reverse ot gnirts eht si siht

最佳答案

加上@alexd 的建议,以下是更新后的程序,并进行了一些修复:

#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;
}

关于c - 在 C 中编写程序来反转字符串中的单词时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29243374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com