主要實現對一個字符的反轉輸出,例如,將字符串“abcdefg”反轉輸出為“gfedcba”。對一個句子的反轉輸出,例如,將句子“I am a student.”反轉輸出為“student. a am I”。其中的一個實現代碼如下:
/** * * @author JiaJoa * 實現對字符串的反轉,對句子單詞的反轉 */
public class StringReverse { public static void main(String[] args){ String str = "abcdefg"; System.out.println(StringReverse.strReverse(str)); String sentence = "I am a student."; System.out.println(StringReverse.sentenceReverse(sentence)); } //字符串的反轉輸出
public static String strReverse(String str){ StringBuffer sb = new StringBuffer(str); return sb.reverse().toString(); } //句子的反轉輸出
public static String sentenceReverse(String sentence){ String[] strArray = sentence.split("\\s"); StringBuilder sb = new StringBuilder(); for(int i=strArray.length-1;i>=0;i--){ sb.append(strArray[i]+" "); } return sb.toString(); } }