日期:2014-05-20  浏览次数:20647 次

写一个类倒叙输出“hello,world”
写一个类倒叙输出“hello,world”
这是我面试一家公司的技术面试题,我是这样写的:

import java.util.*;
public class StringChange{
  public static void main(String[] args){
  System.out.println("Please enter the String:");
  String str = new Scanner(System.in).nextLine(); //输入字符串
  String s2[] = str.split("\\s"); // \s 以空格为分隔符拆分字符串,并保存到数组s2里面
  for (int i = s2.length-1; i >= 0; i--) { //反向输出数组
  System.out.print(s2[i]+" "); 
  }
  }
听说有一种方法是用reserve();方法,我不会用,谁会,麻烦给个例子,参考一下

------解决方案--------------------
Java code
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String sth = input.nextLine();
        for (int i = sth.length()-1; i >= 0; i--) {
            System.out.print(sth.charAt(i));
        }
    }

------解决方案--------------------
探讨
Java code
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String sth = input.nextLine();
for (int i = sth.length()-1; i >= 0; i--) {
……