日期:2014-05-20  浏览次数:20641 次

不会C++的悲哀!
各位懂C++的大虾们,能不能帮小第把下面一段代码翻译成java或是C#,不胜感激啊!
以下是反转一个带有'\0'结束符的字符串的代码:
1 void reverse(char *str) {
2 char * end = str;
3 char tmp;
4 if (str) {
5 while (*end) {
6 ++end;
7 }
8 --end;
9 while (str < end) {
10 tmp = *str;
11 *str++ = *end;
12 *end-- = tmp;
13 }
14 }
15 }

------解决方案--------------------
C/C++ code

//不要被结束符忽悠
void reverse(char *str) {//传入一个指向字符串的指针str
  char * end = str;//把指针str赋给指针end,于是2个指针指向同一个位置
  char tmp;//临时变量,你懂的
  if (str) {//如果指针存在
    while (*end) {//end指针指向的位置一直后移,直到指向结束符'\0'的下一个跳出while,只是end指向结束符'\0'
    ++end;
    }
    --end;//end指针前移一位,指向字符串最后一位
    while (str < end) {//当str指针在end指针之前的时候交换
      tmp = *str;//end和str指针指向的位置上的字符对换,换完之后str后移,end前移
      *str++ = *end;
      *end-- = tmp;
    }
  }
}