反转C风格的字符串

时间:2015-06-27 23:08:09

标签: c++

编写代码以反转C风格的字符串。 (C风格的字符串表示“abcd”表示为五个字符,包括空字符。) 什么都没打印出来。为什么?

void ReverseString(char *p){
    int length = strlen(p);
    for (int i = 0, j = length; i < j; i++, j--){
        swap(p[i], p[j]);
    }

}


int main()
{
    char a[] = "12345";
    ReverseString(a);
    cout << a;
    system("pause");
    return 0;
}

2 个答案:

答案 0 :(得分:5)

您将字符串末尾的AngularJS终结符字符交换到最开头。因此,<ul> <!-- ngRepeat: st in styles --> <li class="active ng-scope"> <a title="Test Style"> <span class="image" style="background-image: url(http://www.bestvinyl.dev/sites/local/main/assets/img/styles/alpha-style.png);"></span> </a> </li><!-- end ngRepeat: st in styles --> <li class="ng-scope"> <a title="Closed Picket"> <span class="image" style="background-image: url(http://www.bestvinyl.dev/sites/local/main/assets/img/styles/closed-picket.png);"></span> </a> </li> </ul> 打印,直到找到第一个'\0'字符,不打印任何内容。使用cout排除它。

但更好:这已在标准库中实现:

\0

将算法用于手工制作的代码通常是一个非常好的主意,因为它更不容易出错并且通常更有效。

答案 1 :(得分:-1)

public class Reverse {
  public static void main(String[] args) {
    StringBuffer s = new StringBuffer("Xmen Logan");
    s.append('\0');

    System.out.println("C-style string---" + s);

    reverse(s);


  }

  public static void reverse(StringBuffer s) {
  int length = s.length();
  char[] chars = new char[length];

  int j = 0;
  for(int i = length-1; i>=0; i--) {
    chars[j++] = s.charAt(i);

  }

  String reverseString = new String(chars);

  System.out.println("Reverse String ------" + reverseString);

}
}