0

我正在尝试编写一个函数来反转字符串:如果字符串输入是"Hello World",则函数应该返回"dlroW olleH"。但是,当我运行我的函数时,字符串保持不变:

void reversestring(char* s) {
    char tmp;   //tmp storing the character for swaping
    int length; //the length of the given string
    int i;      //loop counter

    //reverse the string of even length
    length = strlen(s);
    if (length % 2 == 0) { //if the length of the string is even
        for(i = 0; i < (int) (length / 2);i++) {
            tmp = s[length - i];
            s[length - i] = s[i];
            s[i] = tmp;
        }
    }

    //reverse the string of odd length
    if (length % 2 == 1) { //if the length of the string is odd
        for(i = 0; i < (int) ((length + 1) / 2);i++) {
            tmp = s[length + 1];
            s[length + 1] = s[i];
            s[i] = tmp;
        }
    }
}
4

2 回答 2

1

你只需要一个循环来处理字符串。的对称特征s[i]s[length-i-1],

void reverse(char* s) {
  char tmp; //tmp storing the character for swaping
  int length; //the length of the given string
  int i; //loop counter

  //reverse the string of even length
  length = strlen(s);

  if (length < 2) return;

      for(i = 0; i < (int) (length / 2);i++){
          tmp = s[length - i - 1];
          s[length - i - 1] = s[i];
          s[i] = tmp;
      }
}

示例:

abcde
01234

长度为 5,length / 22(整数除法)。长度是奇数,但您不必移动中心字符。需要交换的字符

(0,4), (1,3)

测试:

int main () {
    char x[] = "Hello World";
    reverse(x);
    printf("%s \n",x );
    return 0;
}

印刷

 dlroW olleH
于 2013-02-26T07:58:30.417 回答
0

您在索引方面落后一分。的对称s[0]不是s[length- 0],而是s[length-0-1]

至于奇怪的情况,我不明白你到底想做什么,但似乎你很容易在每次迭代中越界。

于 2013-02-26T07:50:09.713 回答