Java实现一个字符串的反转

时间:2023-01-07 10:35:48

方法一:

 1 public class reverseString {
 2 public static void main(String[] args) {
 3     String str="ILoveJavaAndPython";
 4     char[] strArray=str.toCharArray();
 5     int len=strArray.length;
 6     char temp;
 7     for(int i=0;i<len/2;i++){
 8         temp=strArray[i];
 9         strArray[i]=strArray[len-i-1];
10         strArray[len-i-1]=temp;
11     }
12     String strAfter=String.valueOf(strArray);
13     System.out.println("Before:"+str);
14     System.out.println("After:"+strAfter);
15      
16 }
17 }

方法二:

 1 public class reverseString {
 2 public static void main(String[] args) {
 3     String str="ILoveJavaAndPython";
 4     char[] strArray=str.toCharArray();
 5     int len=strArray.length;
 6  
 7  
 8     Stack<Character> stack=new Stack<Character>();
 9     for(int i=0;i<len;i++)
10         stack.push(strArray[i]);
11     String afterReversed="";
12     for(int i=0;i<len;i++)
13         afterReversed+=stack.pop();
14     System.out.println("Before:"+str);
15     System.out.println("After:"+afterReversed);
16      
17 }
18 }

转自:http://www.cnblogs.com/itdyb/p/6028112.html