原文
Implement a function void reverse(char* str) in C or C++ which reverses a null-terminated string.
译文
用C或者C++实现一个void reverse(char* str)的函数来逆转一个已null终止的字符串
解答
在C++里,设置俩指针,一个指向字符串头,一个指向尾,然后每次交换一个字符和,指针分别像中间移就行了。这里借用一下Hawstein(http://hawstein.com/posts/1.2.html)的代码好了:
#include <iostream> #include <cstring> using namespace std; void swap(char &a, char &b){ a = a^b; b = a^b; a = a^b; } void reverse2(char *s){ int n = strlen(s); for(int i=0; i<n/2; ++i) swap(s[i], s[n-i-1]); } void reverse1(char *s){ if(!s) return; char *p = s, *q = s; while(*q) ++q; --q; while(p < q) swap(*p++, *q--); } int main(){ char s[] = "1234567890"; reverse1(s); cout<<s<<endl; return 0; }
那么如果在Java里能不能也用同样的方法呢?如果简单的用String并且用到上面相同的方法的话,是不行的。因为String是一个不可变的对象,所以swap其中两个字符并不会真的交换。
在Java里要实现逆转字符串的话可以用以下的方法:
public class Main { public static String reverse(String str) { return new StringBuilder(str).reverse().toString(); } public static void main(String args[]) { String s1 = "i am hawstein."; String s2 = "abcdefghijklmnopqrstuvwxyzABCD1234567890"; System.out.println(reverse(s1)); System.out.println(reverse(s2)); } }