Reverse a given sentence in Java

前端 未结 14 1823
别跟我提以往
别跟我提以往 2020-11-27 04:52

Can anyone tell me how to write a Java program to reverse a given sentence?

For example, if the input is:

\"This is an interview question\"

相关标签:
14条回答
  • 2020-11-27 05:11
    String[] words = sentence.split(" ");
    String[] reversedWords = ArrayUtils.reverse(words);
    String reversedSentence = StringUtils.join(reversedWords, " ");
    

    (using ArrayUtils and StringUtils from commons-lang, but these are easy methods to write - just a few loops)

    0 讨论(0)
  • 2020-11-27 05:11

    Shortest Answer

    public class ReverseSentance {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentance");
        String inputString = sc.nextLine();
    
        String[] words = inputString.split(" ");
    
        List<String> reverseWord = Arrays.asList(words);
        Collections.reverse(reverseWord);
    
        Iterator itr = reverseWord.iterator();
    
        while (itr.hasNext()) {
            System.out.print(itr.next() + " ");
        }
    }
    

    }

    OR

    public class ReverseSentance {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentance");
        String inputString = sc.nextLine();
    
        String[] words = inputString.split(" ");
    
        for (int i = words.length-1 ; i >= 0; i--) {
            System.out.print(words[i] +" ");
        }
    }
    
    0 讨论(0)
  • 2020-11-27 05:15

    nicer approach probably.. had seen the logic somewhere..here is my code which might do the job.

        public class revWords {
    
        public static void main(String[] args) {
    
            revWords obj = new revWords();
            String print = obj.reverseWords("I am God");
            System.out.println(print);
    
        }
    
        public String reverseWords(String words)
        {
          if(words == null || words.isEmpty() || !words.contains(" "))
            return words;
    
          String reversed = "";
          for( String word : words.split(" "))
            reversed = word + " " + reversed;
    
          return reversed;
        }
    
    }
    
    0 讨论(0)
  • 2020-11-27 05:17

    I don't think you should use any library.. 1) Reverse whole string 2) Reverse each word.

    public static void revWord(char[] a) {
    
        // reverse whole
        revWord(a, 0, a.length);
    
        int st = -1;
        int end = -1;
    
        for (int i = 0; i < a.length; i++) {
    
            if (st == -1 && a[i] != ' ') {
                st = i;
            }
            if (end == -1 && a[i] == ' ' ) {
                end = i;
            }
            if(i == a.length-1){
                end=i+1;
            }
    
            if (st != -1 && end != -1) {
                revWord(a, st, end );
    
                st = -1;
                end = -1;
            }
    
        }
    
    }
    
    public static void revWord(char[] a, int s, int l) {
        int mid = (l - s) / 2;
        l--;
    
        for (int i = 0; i < mid; i++, l--) {
            char t = a[s+i];
            a[s+i] = a[l];
            a[l] = t;
        }
    }
    

    `

    0 讨论(0)
  • 2020-11-27 05:19

    a every boring bit of java:

    List<String> l = new ArrayList<String>(Arrays.asList("this is an interview question".split("\\s")));
    Collections.reverse(l);
    StringBuffer b = new StringBuffer();
    for( String s : l ){
        b.append(s).append(' ');
    }
    b.toString().trim();
    

    in groovy it's a little bit more readable:

    "this is an interview question"
        .split("\\s")
        .reverse()
        .join(' ')
    
    0 讨论(0)
  • 2020-11-27 05:22

    Just being different: a recursive solution. Doesn't add any extra spaces.

    public static String reverse(String s) {
       int k = s.indexOf(" ");
       return k == -1 ? s : reverse(s.substring(k + 1)) + " " + s.substring(0, k);
    }
    
    
    System.out.println("[" + reverse("This is interview question") + "]");
    // prints "[question interview is This]"
    

    I will also improve on the split solution by using \b instead (it's so obvious!).

        String[] parts = "Word boundary is better than space".split("\\b");
        StringBuilder sb = new StringBuilder();
        for (int i = parts.length; i --> 0 ;) {
            sb.append(parts[i]);
        }
        System.out.println("[" + sb.toString() + "]");
        // prints "[space than better is boundary Word]"
    
    0 讨论(0)
提交回复
热议问题