本帖最后由 耿渊博 于 2014-3-31 10:16 编辑
以下代码可以实现将字符串整个反转,如何实现部分反转呢?- package com.Thread;
- public class StringTest2 {
- public static void sop(String str){
- System.out.println(str);
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String s = " abc def ";
- sop("("+s+")");
- s = reverseString(s);
- sop("("+s+")");
-
- }
-
- public static String reverseString(String s){
- //字符串变数组
- char[] chs = s.toCharArray();
-
- //反转数组
- reverse(chs);
-
- //将数组转换成字符串
- return new String(chs);
- }
-
- private static void reverse(char[] arr){
- for(int start=0,end=arr.length-1;start<end;start++,end--){
- swap(arr,start,end);
- }
- }
-
- private static void swap(char[] arr,int x,int y){
- char temp = arr[x];
- arr[x] = arr[y];
- arr[y] = temp;
- }
- }
复制代码
|