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); } }