3

I have written the following code to reverse an input String:

  Scanner s = new Scanner(System.in);
  System.out.println("Please enter a sentence:");
  String sentence = s.nextLine();

  String[] words = sentence.split(" ");
  String reversedSentence = "";

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

  System.out.println(reversedSentence);

However it is not giving me the result I want. I need the punctuation to be part of the word it is attached to, but still to switch to the right side of the word. For example if you input

“The quick brown fox jumps over the lazy dog”

I want the output to be

“dog lazy the over jumps fox brown quick The”

What I am actually getting is:

dog” lazy the over jumps fox brown quick “The

3
  • 2
    You are only interested for the quotes at the start and the end ? What about punctuation in the middle of the sentence ? Nov 24, 2015 at 17:02
  • Looks like a special case you'll have to deal with. You could put an if (words[0].contains("\"")) to check to see if a double quote exists. You may want to do this after your for loop.
    – Clark Kent
    Nov 24, 2015 at 17:02
  • 1
    Before 'System.out.println(reversedSentence);' add line 'reversedSentence = "\"" + reversedSentence.replace("\"", "") + "\"";' Nov 24, 2015 at 17:09

3 Answers 3

3

If you just want to handle double quotes at the start and end of the input, just reverse the substring and add them later. E.g.

if (sentence.startsWith("\"") && sentence.endsWith("\"")) {
    sentence = sentence.substring(1, sentence.length()-1);
}

and finally after splitting, reversing and concatenating print:

System.out.println('"' + reversedSentence + '"');

Also 2 recommendations :

1) Your for loop leaves a trailing space. Don't add a space for the last word
2) You should use a StringBuilder to concatenate strings. E.g.

StringBuilder reversedSentence = new StringBuilder();

for (int i = words.length - 1; i > 0; i--) {
    reversedSentence.append(words[i]).append(' ');
}
reversedSentence.append(words[0]);
System.out.println('"' + reversedSentence.toString() + '"');
1
  • 1
    In the top part of this answer, the substring parameters are incorrect because substrings accept (int inclusive, int exclusive) so therefore it should be: if (sentence.startsWith("\"") && sentence.endsWith("\"") { sentence = sentence.substring(1, sentence.length()-1); } Feb 27, 2019 at 19:46
1

If the punctuation opens and closes as well. Like in your example. You could use something like this:

It's very dirty. I'll edit it later. I don't do java much.

    String[][] punctuations = new String[][] {
            {"(", ")"},
            {"“", "”"}
    };

    for (String[] punctuation : punctuations) {
        if (sentence.contains(punctuation[0])) {
            int index_0 = sentence.indexOf(punctuation[0]);
            int index_of_next_space = sentence.indexOf(" ", index_0);
            String old_string_0 = sentence.substring(index_0, index_of_next_space);
            String new_string_0 = old_string_0.replace(punctuation[0], "") + punctuation[1];

            int index_1 = sentence.indexOf(punctuation[1]);
            int index_of_last_space = sentence.lastIndexOf(" ", index_1);
            String old_string_1 = sentence.substring(index_of_last_space+1, index_1 + 1);
            String replaced_string_1 = punctuation[0] + old_string_1.replace(punctuation[1], "");
            sentence = sentence.replace(old_string_0, new_string_0);
            sentence = sentence.replace(old_string_1, replaced_string_1);
        }
    }

Now reverse your string.

Input:

“The (quick brown's) fox jumps over the lazy dog”

Output:

“dog lazy the over jumps fox (brown's quick) The”

This can be improved. Like I said before, I don't do java much :/.

0

Break the string into array and use Collections.reverse() as follows:

public class StringReverse {

 public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Please enter a sentence:");
        String sentence = s.nextLine();
        String[] array = sentence.replaceAll("\\“|”", "").split(" ");
        StringBuilder sb = new StringBuilder();
        List<String> list = Arrays.asList(array);
        Collections.reverse(list);
        array = (String[]) list.toArray();
        for (int i = 0; i < array.length; i++) {
            sb.append(array[i]).append(" ");
        }
        System.out.println(sentence.charAt(0)
                + sb.toString().replaceAll(" $", "")
                + sentence.charAt(sentence.length() - 1));
        s.close();
    }
}

With Java 8 Arrays.stream, it is as simple as:

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;

public class StringReverse {

    Scanner s = new Scanner(System.in);
    System.out.println("Please enter a sentence:");
    String sentence = s.nextLine();
    StringBuilder sb = new StringBuilder();
    Arrays.stream(sentence.replaceAll("\\“|”", "").split(" "))
            .collect(Collectors.toCollection(ArrayDeque::new))
            .descendingIterator()
            .forEachRemaining(e -> sb.append(e).append(" "));
    System.out.println(sentence.charAt(0)
            + sb.toString().replaceAll(" $", "")
            + sentence.charAt(sentence.length() - 1));
    s.close();
}
2
  • Next time read the question before answering. Nov 24, 2015 at 17:50
  • @RaghavSharma: missed the quotes because of code formatting issues, anyways fixed it now! Nov 25, 2015 at 7:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.