函数不会正确地反转字符串

时间:2016-05-13 18:12:01

标签: visual-c++ c-strings

#include <iostream>
#include <cstring>
using namespace std;




void reverseString(char s[])
{
    int length = strlen(s);
    for (int i = 0; s[i] != '\0'; i++) {
        char temp = s[i];
        s[i] = s[length - i - 1];
        s[length - i - 1] = temp;

        cout << s[i];   //this ends up printing "eooe" instead of reversing the whole string
    }
}

int main()
{ 
    char a[] = "Shoe"; 
    reverseString(a);

    return 1;
}

我想知道算法在哪里弄乱,我可以做些什么来修复它,也许我忽略了一些东西,因为当我试图在一张纸上解决它时它似乎正常工作。

2 个答案:

答案 0 :(得分:2)

您的算法是正确的,但需要稍加修改,您必须运行length/2次算法。它会阻止您的字符串再次交换内容,即i = 2 s = eohs,但它会再次ho交换。尝试插入断点以进一步理解它。我稍微修改了你的功能。

char* reverseString(char s[])
{
    int length = strlen(s);
    for (int i = 0; i<length/2; i++)
    {
        char temp = s[i];
        s[i] = s[length - i - 1];
        s[length - i - 1] = temp;
        //cout << s[i];   //this ends up printing "eooe" instead of reversing the whole string
    }

    return s;
}

int main()
{
    char a[] = "Shoe";
    cout<<reverseString(a);
    system("pause");
    return 1;
}

答案 1 :(得分:0)

使用以下代码:

#include <stdio.h>

void strrev(char *p)
{
  char *q = p;
  while(q && *q) ++q;
  for(--q; p < q; ++p, --q)
    *p = *p ^ *q,
    *q = *p ^ *q,
    *p = *p ^ *q;
}

int main(int argc, char **argv)
{
  do {
    printf("%s ",  argv[argc-1]);
    strrev(argv[argc-1]);
    printf("%s\n", argv[argc-1]);
  } while(--argc);

  return 0;
}