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

文字列を処理するために必要なループは 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

長さは 5length / 2です2(整数除算)。長さは半端ないですが、中心人物を動かす必要はありません。交換が必要なキャラクター

(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

インデックス作成で 1 つずれています。の対称s[0]s[length- 0]ではなくs[length-0-1]です。

奇妙なケースについては、正確に何をしようとしているのかわかりませんが、反復ごとに簡単に範囲外に出てしまうようです。

于 2013-02-26T07:50:09.713 に答える