我的反向功能出了什么问题

时间:2013-02-26 07:47:57

标签: c

我正在尝试编写一个函数来反转字符串:如果字符串输入为"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;
        }
    }
}

2 个答案:

答案 0 :(得分: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(整数除法)。 length 是奇数,但您不必移动中心字符。需要交换的字符

(0,4), (1,3)

测试:

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

打印

 dlroW olleH

答案 1 :(得分:0)

你在索引中不在乎。 s[0]的对称不是s[length- 0],而是s[length-0-1]

至于奇怪的情况,我不明白你究竟尝试做什么,但似乎你很容易在每次迭代时超出范围。