14

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"

The output must be:

"question interview an is this"

Tot Zam
  • 8,406
  • 10
  • 51
  • 76
giri
  • 26,773
  • 63
  • 143
  • 176
  • You should probably consider taking Java certification classes, as they will teach you commonly used Java library classes. You'll then have the tools needed to accomplish such tasks. – Marcus Adams Apr 26 '10 at 13:29
  • 1
    Reverse the string first. Reverse the words then. It takes two pass but very clean. Can be done in 1 pass as well. – Jack Apr 26 '10 at 13:35
  • 1
    @jack, I think your first word was meant to be "split", yes? – CPerkins Apr 26 '10 at 14:00
  • 2
    @CPerkins: well, "the question" -> "noitseuq eht" -> "question the" still works, and I suspect that is what Jack meant since answerers have already posted your way. – Pops Apr 26 '10 at 14:06
  • @CPerkins No. What I meant was (in python):
    str = "this is interview question"
    str1 = str[::-1]
    print str1
    for word in str1.split(" "):
    print word[::-1]
    – Jack Apr 26 '10 at 14:14
  • for exa: this is interview question => noitseuq weivretni si siht => question interview is this – Jack Apr 26 '10 at 14:15
  • See also: http://stackoverflow.com/q/1009160/466738 – Adam Michalik Dec 06 '15 at 09:50

14 Answers14

24

You split the string by the space then iterate over it backwards to assemble the reversed sentence.

String[] words =  "This is interview question".split(" ");

String rev = "";
for(int i = words.length - 1; i >= 0 ; i--)
{
   rev += words[i] + " ";
}

// rev = "question interview is This "

// can also use StringBuilder:
StringBuilder revb = new StringBuilder();
for(int i = words.length - 1; i >= 0 ; i--)
{
   revb.append(words[i]);
   revb.append(" ");
}
// revb.toString() = "question interview is This "
Tot Zam
  • 8,406
  • 10
  • 51
  • 76
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 7
    Won't this add a trailing space? – Skilldrick Apr 26 '10 at 13:26
  • 2
    Is there a reason you're concatenating to a `string` (which creates a new `string` object every time) instead of using a `StringBuilder`? – Christopher Parker Apr 26 '10 at 13:27
  • @Christopher Parker - Simply showing the principle. This can of course be adapted to be more performant (if needed). – Oded Apr 26 '10 at 13:31
  • 1
    @Skilldrick - `Rev.trim();` to remove the trailing space. Not that the question specified, but like you, I dislike extra spaces like that. – Onion-Knight Apr 26 '10 at 13:45
  • I wouldn't use trim() - It creates an entirely new String. Better to perform a second check of i within the loop IMHO. – Adamski Apr 26 '10 at 14:09
  • https://codereview.stackexchange.com/a/60913/146446 explains this code in more detail, and also has great unit tests. – Tot Zam Aug 11 '17 at 21:23
23
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)

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 7
    Using an outside library for an interview question this simple isn't going go over that well. – D'Nabre Apr 26 '10 at 13:38
  • 5
    well. that over go to going isn't simple this question interview an for library outside an Using – Powerlord Apr 26 '10 at 13:44
  • 5
    @D'Nabre - if you know commons-lang well enough to write that code, I think it would go VERY well over that well. – Thorbjørn Ravn Andersen Apr 26 '10 at 13:50
  • 1
    @D'Nabre I don't think so. If they ask you to explain how are these utility methods implemented, you'd always be able to explain, but thus you are increasing the elegance of your code. What if these methdos were present in `java.util.Arrays`? – Bozho Apr 26 '10 at 13:50
  • If someone demonstrated appreciation of the *know and use the libraries* guideline in an interview, I'd definitely consider that a plus. – Jonik Apr 26 '10 at 14:08
  • The last line should use `StringUtils` rather than `ArrayUtils`. – Rose Perrone Apr 12 '12 at 17:02
  • Here in India they tell you "please do not use any library methods, it won't be considered" that in fact wont go well. – Sujal Mandal Aug 23 '14 at 19:56
  • Not sure if this solution takes care of double spaces? – user1529412 Feb 12 '15 at 01:00
  • for double-spaces you can split around " +". Or normalize first. – Bozho Feb 15 '15 at 13:49
21

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]"
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • nice, i really liked the recursive solution design, but the iteration + string builder has to be faster, correct? – user797963 Nov 18 '13 at 03:46
6

Just split it on a space character into a string array, then loop over the array in reverse order and construct the output string.

String input = "This is interview question";
String output = "";
String[] array = input.split(" ");
for(int i = array.length-1; i >= 0; i--)
{
    output += array[i];
    if (i != 0) { output += " "; }
}
Rich Adams
  • 26,096
  • 4
  • 39
  • 62
6

Bozho already gave a great Java-specific answer, but in the event you ever need to solve this problem without Java API methods:

To reverse, you can simply pop individual words onto a stack and pop them all back off when there are no words left.

(Just to be extra clear, Java does provide a Stack class, so it is possible to use this method in Java as well).

Pops
  • 30,199
  • 37
  • 136
  • 151
3

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(' ')
Gareth Davis
  • 27,701
  • 12
  • 73
  • 106
3

I also give it a try: Here's a version using a stack and a scanner:

String input = "this is interview question";
Scanner sc = new Scanner(input);
Stack<String> stack = new Stack<String>();

while(sc.hasNext()) {
    stack.push(sc.next());
}

StringBuilder output = new StringBuilder();

for(;;) { // forever
    output.append(stack.pop());

    if(stack.isEmpty()) {
        break; // end loop
    } else {
        output.append(" ");
    }
}
Searles
  • 1,447
  • 1
  • 11
  • 26
2
public class ReverseString {

    public void reverse(String[] source) {

        String dest = "";
        for (int n = source.length - 1; n >= 0; n--) {
            dest += source[n] + " ";
        }
        System.out.println(dest);

    }

    public static void main(String args[]) {
        ReverseString rs = new ReverseString();
        String[] str = "What is going on".split(" ");
        rs.reverse(str);

    }

}
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
gmhk
  • 15,598
  • 27
  • 89
  • 112
1

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;
    }
}

`

Rajender Saini
  • 594
  • 2
  • 9
  • 24
1

No one has mentioned a vanilla Java 8 based solution yet, which is the same as Bozho's, but without any third-party libraries. So here it is:

String input = "This is interview question";

List<String> list = Arrays.asList(input.split(" "));
Collections.reverse(list);
System.out.println(list.stream().collect(Collectors.joining(" ")));
Community
  • 1
  • 1
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
1

please try below solution, this is working for me.

public class reverseline {

public static void main(String[] args) {
    // TODO Auto-generated method stub

        String str="This is interview question";
    String words[]=str.split(" ");
    for(int i=words.length-1;i>=0;i--){
        System.out.print(words[i]+" ");
    }
}

}
Amol Udage
  • 2,917
  • 19
  • 27
1

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;
    }

}
gammabowl
  • 31
  • 5
0

Before StringTokenizer was declared legacy, many used StringTokenizer for this. Thought I would just leave it here.

String sentence = "This is interview question";
String reversed = "";
StringTokenizer tokens = new StringTokenizer(sentence); 

while (tokens.hasMoreTokens()) { // Loop through each token
    reversed =  tokens.nextToken() + ' ' + reversed; //add to start
}

System.out.println(reversed.trim());
Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74
0

Shortest Answer

public class ReverseSentence {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence");
        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 ReverseSentence {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence");
        String inputString = sc.nextLine();

        String[] words = inputString.split(" ");

        for (int i = words.length-1 ; i >= 0; i--) {
            System.out.print(words[i] +" ");
        }
    }

}
Matt Ke
  • 3,599
  • 12
  • 30
  • 49
Rishabh Agarwal
  • 2,374
  • 1
  • 21
  • 27