- public class StringTest4 {
- public static void main(String[] args){
- String s = "Hello World";
- System.out.println("Before: "+ s);
- System.out.println("After: "+ reverseStr(s));
- }
- public static String reverseStr(String s){
- //将2字符串转换为字符数组,以便于交换
- char[] ch = s.toCharArray();
- //同时从头和尾开始遍历字符数组,交换头尾元素
- for(int start = 0, end = s.length()-1; start < end; start++, end--){
- char temp = ch[start];
- ch[start] = ch[end];
- ch[end] = temp;
- }
- //将字符数组转换为字符串
- return new String().valueOf(ch);
- }
- }
复制代码
|
|