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();
}
}
该博客展示了一段Java代码,通过StringTokenizer类实现字符串反转功能。定义了分隔符,在reverse方法中对输入字符串进行处理,最后在testReverse方法里对多个句子进行反转测试,并在main方法中调用测试方法输出结果。
523

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



