一道简单的java面试题
题目:
实现一个字符串的颠倒,如把"abcde",转换成"edcba".
希望大家提供自己的实现方式。下面是我的:
public class Transfer {
?/**
? * @param args
? */
?public static void main(String[] args) {
??String oldString = "abcdefg";
??String newString = transferString(oldString);
??System.out.println("the reulst string is " + newString);
?}
?/**
? * The transfer method
? *
? * @param oldString
? * @return
? */
?private static String transferString(String oldString) {
??StringBuffer newStringBuffer = new StringBuffer(oldString);
??int length = oldString.length();
??for (int i = 0; i < length / 2 + 1; i++) {
???char a = oldString.charAt(i);
???char b = oldString.charAt(length - i - 1);
???newStringBuffer.replace(i, i + 1, String.valueOf(b));
???newStringBuffer.replace(length - i - 1, length - i, String
?????.valueOf(a));
??}
??return new String(newStringBuffer);
?}
}
import java.io.*;import java.util.*;/* * 将"abcdefg"输出成"gfedcba" */public class Test3 {public static void main(String[] args){String str="abcdefg";String str1="";for(int i=0;i<str.length();i++){str1=str1+str.substring(str.length()-i-1, str.length()-i);}System.out.println(str1);}}