0

我尝试使用缓冲的 string.reverse(); 但我想反转句子的每个单词。所以我试试这个..

 for(int a = 0;a <= msgLength; a++){
           temp += msg.charAt(a);
           if((msg.charAt(a) == '')||(a == msgLength)){
           for(int b = temp.length()-1; b >= 0; b--){
               encrypt_msg += temp.charAt(a);
               if((b == 0) && (a != msgLength))
                   encrypt_msg += "";
           }
           temp = "";
       }
       }

请帮我简化这个逻辑。字符串是用户定义的。我想在 jtextfields 中打印反转的字符串。

4

3 回答 3

2

尝试以下简单代码:

String sentence= "This is sentence";
String[] words=sentence.split(" ");
for(String word: words){
 System.out.println(new StringBuilder(word).reverse());
}
于 2013-10-07T14:39:35.360 回答
0

那里有你的答案...

StringTokenizer st = new StringTokenizer("这是一个测试"); 字符串 strRev="";

    while (st.hasMoreTokens()) {
     StringBuffer revers=new StringBuffer(st.nextToken());
     strRev=strRev+" "+revers.reverse().toString();
 }

试试看..!!

于 2013-10-07T14:52:40.807 回答
0

有一个名为split()的方法

您可以像这样使用这种方法分离令牌。

String s = "hello how are you";
String[] s2 = s.split(" ");

现在 s2 包含每个单词作为数组元素。

现在您可以通过遍历数组来反转。

于 2013-10-07T14:39:51.947 回答