【问题标题】:How to reverse words of a Java String如何反转Java字符串的单词
【发布时间】:2013-04-01 08:44:37
【问题描述】:

我正在尝试编写一个程序来从扫描仪中获取字符串的输入,但我想分解输入的字符串并颠倒单词的顺序。这就是我到目前为止所拥有的。

Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
StringBuilder welcome = new StringBuilder(input.next());
int i;
for( i = 0; i < welcome.length(); i++ ){
    // Will recognize a space in words
    if(Character.isWhitespace(welcome.charAt(i))) {
        Character a = welcome.charAt(i);
    }   
}

我想要做的是在它识别出空格之后,捕获它之前的所有内容,等等每个空格,然后重新排列字符串。

【问题讨论】:

  • 可能想在某处使用String.substring()...
  • 您可以利用String.splitCollections.reverse
  • 另外input.next() 只会返回一个词。相反,您可以使用input.nextLine() 获取整行。

标签: java string input


【解决方案1】:

问题后编辑。

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

   public static void main( String[] args ) {
      final String welcome = "How should we get words in string form a List?";
      final List< String > words = Arrays.asList( welcome.split( "\\s" ));
      Collections.reverse( words );
      final String rev = words.stream().collect( Collectors.joining( ", " ));
      System.out.println( "Your sentence, reversed: " + rev );
   }
}

执行:

Your sentence, reversed: List?, a, form, string, in, words, get, we, should, How

【讨论】:

  • 类型列表不是通用的,不能参数化
  • 得到了eclipse自动导入awt.list,awt gui中使用的'
  • 但还有一个问题,我们应该如何获取目前它给出的字符串形式的单词,如集合或数组/列表
【解决方案2】:

我确实建议先反转整个字符串。 然后反转两个空格之间的子串。

public class ReverseByWord {

    public static String reversePart (String in){
        // Reverses the complete string
        String reversed = "";
        for (int i=0; i<in.length(); i++){
            reversed=in.charAt(i)+reversed;
        }
        return reversed;
    }

    public static String reverseByWord (String in){
        // First reverses the complete string
        // "I am going there" becomes "ereht gniog ma I"
        // After that we just need to reverse each word.
        String reversed = reversePart(in);
        String word_reversal="";
        int last_space=-1;
        int j=0;
        while (j<in.length()){
            if (reversed.charAt(j)==' '){
                word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, j));
                word_reversal=word_reversal+" ";
                last_space=j;
            }
            j++;
        }
        word_reversal=word_reversal+reversePart(reversed.substring(last_space+1, in.length()));
        return word_reversal;
    }

    public static void main(String[] args) {
        // TODO code application logic here
        System.out.println(reverseByWord("I am going there"));
    }
}

【讨论】:

  • 谢谢!这很快,真的很有帮助,不胜感激。
【解决方案3】:

这里是你可以在输入的字符串中反转单词的方法:

Scanner input = new Scanner(System.in);
System.out.println("Enter your string");
String s = input.next();

if(!s.trim().contains(' ')) {
   return s;
}
else {

   StringBuilder reversedString = new StringBuilder();
   String[] sa = s.trim().split(' ');

   for(int i = sa.length() - 1; i >= 0: i - 1 ) {

      reversedString.append(sa[i]);
      reversedString.append(' ');
   }

   return reversedString.toString().trim();
}

希望这会有所帮助。

【讨论】:

    【解决方案4】:

    如果你想减少代码行数,我想你可以看看我的代码:

    package com.sujit;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class StatementReverse {
        public static void main(String[] args) throws IOException {
            String str;
            String arr[];
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter a string:");
            str = br.readLine();
            arr = str.split("\\s+");
    
            for (int i = arr.length - 1;; i--) {
                if (i >= 0) {
                    System.out.print(arr[i] + " ");
                } else {
                    break;
                }
    
            }
        }
    }
    

    【讨论】:

      【解决方案5】:
      public class StringReverse {
          public static void main(String[] args) {
              String str="This is anil thakur";
              String[] arr=str.split(" ");
      
              StringBuilder builder=new StringBuilder("");
              for(int i=arr.length-1; i>=0;i--){
                  builder.append(arr[i]+" ");
              }
              System.out.println(builder.toString());
          }
      
      }
      
      Output: thakur anil is This 
      

      【讨论】:

        【解决方案6】:
        public class ReverseWordTest {
        
          public static String charRev(String str) {
        
            String revString = "";
            String[] wordSplit = str.split(" ");
        
            for (int i = 0; i < wordSplit.length; i++) {
        
              String revWord = "";
              String s2 = wordSplit[i];
        
              for (int j = s2.length() - 1; j >= 0; j--) {
                revWord = revWord + s2.charAt(j);
              }
        
              revString = revString + revWord + " ";
            }
            return revString;
          }
        
          public static void main(String[] args) {
            System.out.println("Enter Your String: ");
            Scanner sc = new Scanner(System.in);
            String str = sc.nextLine();
            System.out.println(charRev(str));
          }
        

        【讨论】:

          【解决方案7】:
              public static void main(String[]args)
          {
          String one="Hello my friend, another way here";
          String[]x=one.split(" ");
          one="";
          int count=0;
          for(String s:x){
              if(count==0||count==x.length) //that's for two edges.
                one=s+one;
              else
                one=s+" "+one;
              count++;
          }
          System.out.println(one); //reverse.
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-12-13
            • 1970-01-01
            • 1970-01-01
            • 2021-04-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多