来自 javaeye
[code]import java.util.StringTokenizer;
public class Test{
public static final String SEPARATORS = " ,\t:'';?!";
public static String reverse(String input){
StringTokenizer st = new StringTokenizer(input, SEPARATORS, true);
StringBuffer words = new StringBuffer("");
while (st.hasMoreTokens()) {
words.insert( 0, st.nextToken() );
}
return words.toString();
}
public void testReverse(){
String[] sentences = new String[]{
"Hello, world!",
"I am a student",
"Am I a student? yes, or no",
"Am I a student ? yes , or no",
"Zhuang says:'It's just a coding game.'"
};
for (int i = 0; i < sentences.length; i++)
System.out.println("Sentence[" + i + "]=[" + sentences[i]+"], " +
"After reversed: [" + Test.reverse(sentences[i])+"]");
}
public static void main(String[] args){
new Test().testReverse();
}
} [/code]
[code]import java.util.StringTokenizer;
public class Test{
public static final String SEPARATORS = " ,\t:'';?!";
public static String reverse(String input){
StringTokenizer st = new StringTokenizer(input, SEPARATORS, true);
StringBuffer words = new StringBuffer("");
while (st.hasMoreTokens()) {
words.insert( 0, st.nextToken() );
}
return words.toString();
}
public void testReverse(){
String[] sentences = new String[]{
"Hello, world!",
"I am a student",
"Am I a student? yes, or no",
"Am I a student ? yes , or no",
"Zhuang says:'It's just a coding game.'"
};
for (int i = 0; i < sentences.length; i++)
System.out.println("Sentence[" + i + "]=[" + sentences[i]+"], " +
"After reversed: [" + Test.reverse(sentences[i])+"]");
}
public static void main(String[] args){
new Test().testReverse();
}
} [/code]
Java字符串逆序
本文介绍了一个简单的Java程序,用于将包含特定分隔符的字符串逆序排列。通过使用StringTokenizer类来拆分字符串并将其逆序输出。示例中包含了多种句子结构以展示该方法的有效性。

8948

被折叠的 条评论
为什么被折叠?



