定义一个方法,实现字符串反转
键盘录入一个字符串,调用该方法后,在控制台输出结果
例如,键盘录入abc,输出结果cba
示例代码:
public class HomeworkTest03 { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("请输入你要反转的字符串:"); String s1 = s.next(); System.out.println(reverse(s1)); } /** * 调用String对象的charAt方法,将字符串从后往前依次取出来 * 然后添加到StringBuffer当中去,在转换成String对象 * * @param str * @return */ public static String reserve(String str) { StringBuffer sb = new StringBuffer(); for (int i = str.length() - 1; i >= 0; i--) { sb.append(str.charAt(i)); } return sb.toString(); } public static String reverse(String str) { StringBuffer s = new StringBuffer(str); s.reverse(); return s.toString(); } public static String reverse01(String s) { String s1 = ""; for (int i = s.length(); i>=0;i++) { char c = s.charAt(i); s1 += c; } return s1; } }
运行结果: