标签:char -- 输入 line 字符 eal pen build can
将一个字符串str的内容颠倒过来,并输出。str的长度不超过100个字符。 如:输入“I am a student”,输出“tneduts a ma I”。
package test; import java.util.Scanner; /* 一个句子单词逆序、句子逆序 */ public class exam09 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String str = scanner.nextLine(); reverseAll1(str); reverseAll2(str); reverseAll3(str); } } public static void reverseAll1(String str) { // 方法一 char[] chars = str.toCharArray(); for (int i = 0, j = chars.length - 1; i <= j; i++, j--) { // 两个指针,i向后,j向前 char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } System.out.println(String.valueOf(chars)); } public static void reverseAll2(String str) { // 方法二 StringBuilder sb = new StringBuilder(str); sb.reverse(); System.out.println(sb.toString()); } public static void reverseAll3(String str) { // 方法三 StringBuilder sb = new StringBuilder(); for (int i = str.length() - 1; i >= 0; i--) { sb.append(str.charAt(i)); } System.out.println(sb.toString()); } }
标签:char -- 输入 line 字符 eal pen build can
原文地址:http://www.cnblogs.com/bella-young/p/6409549.html