使用StringBuffer類很容易實現字符串按字符顛倒,如果要實現按單詞顛倒,可以使用 StringTokenizer對象和stack對象。
import java.util.Stack;
import java.util.StringTokenizer;
public class stack {
/**
* @param args
*/
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// TODO Auto-generated method stub
String str="ABCDEFG";
System.out.println(str+"->"+new StringBuffer(str).reverse());
//這個是按字符顛倒
String s="you will never be alone in the darkness";
//向堆棧中壓入元素
@SuppressWarnings("rawtypes")
Stack myStack=new Stack();
StringTokenizer st=new StringTokenizer(s);
while(st.hasMoreTokens())
myStack.push(st.nextElement());
//打印堆棧信息
System.out.println('"'+s+'"'+"backwards by word is:\n\t\"");
while(!myStack.empty()){
System.out.println(myStack.pop());
System.out.println(' ');
}
System.out.println('"');
}
}
輸出結果:
ABCDEFG->GFEDCBA
"you will never be alone in the darkness"backwards by word is:
"
darkness
the
in
alone
be
never
will
you
"