首页 > 解决方案 > 使用while循环在C中反转字符串

问题描述

这段代码基本上应该采用一个字符串,例如它是“abc de fgh”,输出应该是

cba
ed
hgf

此处显示的代码确实将字符串放入一行,但不会反转它们。我在想出那部分以及如何在方法中使用我的论点中的 char* 时遇到了麻烦。在正确方向上的任何帮助都会很棒!

void stringReverse(char* s){

    char* i = 0;
    char* j = strlen(s)-1;
    //in order to swap the characters s[i] and s[j] make a temp
    char* temp;

    while(i < j){
        temp = i;
        i = j;
        j = temp;

        i++;
        j--;
    }
    //end of the while loop means that it reversed everything (no need for if/else)
}

标签: c

解决方案


您的代码似乎混合了使用索引(如0or strlen(s)-1)或使用指针的概念。即使在评论中,您也写了“交换字符s[i]s[j]”,但您将i和声明jchar*变量。

第二个错误是您交换了指针值,而不是指针指向的字符。

您应该决定是否要使用指针或索引来访问字符。

使用指针的解决方案:

void stringReverse(char* s){

    //in order to swap the characters s[i] and s[j] make a temp
    char temp;
    char* i = s;
    /* according to the standard, the behavior is undefined if the result
     * would be one before the first array element, so we cannot rely on
     * char* j = s + strlen(s) - 1;
     * to work correct. */
    char* j = s + strlen(s); 
    if(j > i) j--; // subtract only if defined by the C standard.

    while(i < j){
        temp = *i;
        *i = *j;
        *j = temp;

        i++;
        j--;
    }
    //end of the while loop means that it reversed everything (no need for if/else)
}

使用索引的解决方案:

void stringReverse(char* s){

    size_t i = 0;
    size_t j = strlen(s)-1;
    //in order to swap the characters s[i] and s[j] make a temp
    char temp;

    while(i < j){
        temp = s[i];
        s[i] = s[j];
        s[j] = temp;

        i++;
        j--;
    }
    //end of the while loop means that it reversed everything (no need for if/else)
}

如果启用了足够的警告,编译器应该警告原始源代码中的一些问题。我建议始终启用尽可能多的警告。


推荐阅读