写一个方法,实现字符串的反转,如:输入abc,输出cba 博客分类: Java 字符串反转
程序员文章站
2024-03-16 12:16:40
...
public static String reverse1(String s){ int length = s.length(); StringBuffer result = new StringBuffer(); for(int i=length-1;i>=0;i--){ result.append(s.charAt(i)); } return result.toString(); } public static String reverse2(String s){ int length = s.length(); String result = ""; for(int i=length-1;i>=0;i--){ result += s.substring(i,i+1); } return result; } public static String reverse3(String s){ char[] chars = s.toCharArray(); int length = chars.length; int mid = length/2; char temp; for(int i = 0; i<mid; i++){ temp = chars[i]; chars[i] = chars[length-i-1]; chars[length-i-1] = temp; } return String.valueOf(chars); }