我的函数应该反转两个字符串 - 名字和姓氏。所以 John Smith 的输出应该是 Smith John。问题是,它应该是 void 函数。所以我想应该修改全局数组。我试图对其进行编码 - 我附加了代码,但它不起作用。我的数组保持不变。我认为结论中的某个地方是错误的,我试图在结论中覆盖初始数组“名称”,但它不起作用。请问有什么错误的想法吗?
#include <stdio.h>
#include <string.h>
void reverse(char *name) {
int index = 0;
char first[20];
char second[20];
bool firstName = true;
for (int i = 0; i < strlen(name); i++) {
if (name[i] == ' ') {
firstName = false;
first[i] = '\0';
}
else if (firstName)
first[i] = name[i];
else {
second[index] = name[i];
index++;
}
}
second[index] = ' ';
second[index+1] = '\0';
name = strcat(second, first);
}
int main() {
char name[] = "John Smith";
printf("originally: %s\n", name);
reverse(name);
printf("reversed: %s\n", name);
}
最佳答案
你做错了什么?您无法返回修改后的字符串。将 name = strcat(second,first);
替换为:
strcpy(name, second);
strcat(name, first);
这是一个非常简单的替代解决方案:
#include <stdio.h>
void reverse(char *buf) {
char first[20], last[20];
if (sscanf(buf, "%19s%19s", first, last) == 2) {
sprintf(buf, "%s %s", last, first);
}
}
int main() {
char name[] = "John Smith";
printf("originally: %s\n", name);
reverse(name);
printf("reversed: %s\n", name);
return 0;
}
关于C 在 void 函数中反转单个字符串中的两个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49612210/