这道题毕业找工作的时候常考
[color=blue]输入一个字符串,按相反顺序输出该字符串。如输入1234,输出4321。[/color]
或者
[color=blue]输入一个字符串,按相反顺序输出该字符串。如输入1234,输出4321。[/color]
package test25;
import java.util.*;
public class OperateString {
/**
* @param args
*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("输入字符串,反转输出,0退出!");
String str = s.nextLine();
if (str.equals("0")) {
break;
}
System.out.println(OperateString.reverse(str));
}
}
public static String reverse(String s) {
if (s.length() >= 1) {
return s.substring(s.length() - 1)
+ reverse(s.substring(0, s.length() - 1));
} else {
return "";
}
}
}
或者
package test25;
import java.util.Scanner;
public class StringOperate {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
while (true) {
Scanner scanner = new Scanner(System.in);
String temp = scanner.nextLine();
/*
* for (int i = temp.length() - 1; i >= 0; i--) {
* System.out.print(temp.charAt(i)); }
*/
StringBuilder s1 = new StringBuilder(temp);
// StringBuffer s1 = new StringBuffer(temp);
System.out.println(s1.reverse());
System.out.println();
if (temp.equals("exit")) {
break;
}
}
}
}