1

I need to make a program that takes a user entered sentence and reverses it with proper formatting and punctuation.

Ex:The quick brown fox jumps over the lazy dog.

RESULT: "Dog lazy the over jumps fox brown quick the."

I have seen solutions to this and I can get a correct answer by asking the user for 1 word at a time. However we are specifically asked to ONLY ask the user for the sentence, and then the program does the rest. So the program has to determine how large the array is, and assign each word in the string to a value in the array (i guess?).

So far this is what I have, however I think that I need to use a stringBuffer but I don't know how to implement this.

public class ReverseSentence {

    public static void main(String[] args) {






        String[] sentence = new String[]{IO.readString()};

        for(int counter = 0; counter < sentence.length; counter++){
            System.out.println("Enter Sentence"+(counter+1));
            sentence[counter] = IO.readString();
        }

        System.out.println("The Reversed Sentence is:");
        for(int counter = sentence.length - 1; counter >= 0; counter--){
            System.out.print(sentence[counter]);

        }





    }

}

This is not for a homework assignment, just some practice problems for an upcoming exam, so a full solution would be fine, but if possible, with comment lines so I can see how you did it.

1
  • What does IO.readString() return? One word or the whole sentence? Commented Apr 12, 2015 at 18:18

4 Answers 4

2

You have two distinct problems:

  1. reversing the sentence
  2. capitalising the sentence

Lets do the first part fist:

public static String reverseSentence(final String sentence) {
    final Pattern pattern = Pattern.compile("[^A-Za-z']+");
    final List<String> words = pattern.splitAsStream(sentence)
            .map(String::toLowerCase)
            .collect(toList());
    final StringBuilder reversed = new StringBuilder();
    final ListIterator<String> i = words.listIterator(words.size());
    reversed.append(i.previous());
    while (i.hasPrevious()) {
        reversed
                .append(" ")
                .append(i.previous());
    }
    reversed.append(".");
    return reversed.toString();
}

Double-check the code:

public static void main(String[] args) throws Exception {
    System.out.println(reverseSentence("The quick brown fox jumps over the lazy dog"));
}

dog lazy the over jumps fox brown quick the.

Okay, now we need to capitalise the first word:

public static String capitalise(final String name) {
    return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
}

We just need to use this method on the first word:

public static String reverseSentence(final String sentence) {
    final Pattern pattern = Pattern.compile("[^A-Za-z']+");
    final List<String> words = pattern.splitAsStream(sentence)
            .map(String::toLowerCase)
            .collect(toList());
    final StringBuilder reversed = new StringBuilder();
    final ListIterator<String> i = words.listIterator(words.size());
    reversed.append(capitalise(i.previous()));
    while (i.hasPrevious()) {
        reversed
                .append(" ")
                .append(i.previous());
    }
    reversed.append(".");
    return reversed.toString();
}

Check it again:

Dog lazy the over jumps fox brown quick the.

Sign up to request clarification or add additional context in comments.

1 Comment

Was literally in the middle of asking the other two how I would implement the capitalization. Everything here looks perfect and it works great. Going to run this through debugger a few times to fully understand it. Thank you so much.
2

You can try like this:

public static String reverseString(String input) {
     //from input to this method
     // split input with space and store words
     // in a collection if input is not empty
    Deque<String> words = new ArrayDeque<>();
    for (String word: input.split(" ")) {
        if (!word.isEmpty()) {
            words.addFirst(word);
        }
    }

      //now build output in reverse order of
      // addition to collection if input is not empty
    StringBuilder result = new StringBuilder();
    while (!words.isEmpty()) {
        result.append(words.removeFirst());
        if (!words.isEmpty()) {
            result.append(" ");
        }
    }
    return result.toString();
}

1 Comment

@Bubletan:- I guess OP can add that one. Anyways to capitalize the first word of the string you just have to add this line....String output = input.substring(0, 1).toUpperCase() + input.substring(1);
0

Use Apache Commons StringUtils.

https://commons.apache.org/proper/commons-lang/

String result = StringUtils.capitalize(StringUtils.reverse(StringUtils.uncapitalize(basicString.substring(0,basicString.length()-1)))) + ".";

Comments

0

Try this. This code will give output of all case of format using full stop (.). And read the comment carefully.

Scanner inp = new Scanner(System.in);

String s1 = inp.nextLine();
String s2[] = s1.split(" ");
boolean full_stop = false;
// Printing first character of last string in upper case
System.out.print(Character.toUpperCase(s2[s2.length - 1].charAt(0)));
// Printing rest of the character of last string
if (s2[s2.length - 1].contains(".")) {// checking that (.) is exists then print without (.)
    System.out.print(s2[s2.length - 1].substring(1,s2[s2.length - 1].length() - 1) + " ");
    full_stop = true;
} else {
    System.out.print(s2[s2.length - 1].substring(1, s2[s2.length - 1].length()) + " ");
}
for (int i = s2.length - 2; i >= 0; i--) {
    if (i > 0) {
        System.out.print(s2[i] + " ");
    } else {
        System.out.print(Character.toLowerCase(s2[i].charAt(0)));//converting first string character to lower case
        System.out.print(s2[i].substring(1,s2[i].length()));// last string must not have space after that
    }
}
if (full_stop) {// printing (.) if exists
    System.out.println(".");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.