C 在 void 函数中反转单个字符串中的两个单词

标签 c string reverse

我的函数应该反转两个字符串 - 名字和姓氏。所以 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/

相关文章:

arrays - ruby array hash get key by value 和 value by key

c - 使用 Visual Studio 在 C 中反转字符串

c - 在c中得到 "free(): invalid pointer"

C 崩溃中的检查控制台游戏

r - 在 R 中将数字添加到字母数字字符串的有效方法

c - 将字符串值存储在 int 中

c++ - 使用字符串初始化wchar_t []

reverse - Java 的 BigInteger 符号大小如何工作

python - 重用已知的排序操作对类似未排序的数据进行排序

c - 是什么导致我的二十一点程序在执行任何操作之前崩溃?