Java实现一个字符串的反转

Java小程序实现字符串的反转:

方法一:

public class reverseString {
public static void main(String[] args) {
	String str="ILoveJavaAndPython";
	char[] strArray=str.toCharArray();
	int len=strArray.length;
	char temp;
	for(int i=0;i<len/2;i++){
		temp=strArray[i];
		strArray[i]=strArray[len-i-1];
		strArray[len-i-1]=temp;
	}
	String strAfter=String.valueOf(strArray);
	System.out.println("Before:"+str);
	System.out.println("After:"+strAfter);
	
}
}

 

方法二:

import java.util.Stack;

public class reverseString {
public static void main(String[] args) {
	String str="ILoveJavaAndPython";
	char[] strArray=str.toCharArray();
	int len=strArray.length;


	Stack<Character> stack=new Stack<Character>();
	for(int i=0;i<len;i++)
		stack.push(strArray[i]);
	String afterReversed="";
	for(int i=0;i<len;i++)
		afterReversed+=stack.pop();
	System.out.println("Before:"+str);
	System.out.println("After:"+afterReversed);
	
}
}

 

posted on 2016-11-03 20:36  波比12  阅读(6587)  评论(0编辑  收藏  举报

导航