简体   繁体   中英

Java Reverse a sentence but not punctuation

Input: My name is Bob.

Output: Bob is name My.

I have seen plenty of examples on how to reverse each word and then word sequence in a sentence. However, I do not think I have seen one that I want-example above. This forum was not helpful, because it only focuses on double quote on start and end of a sentence: How to reverse words in a string but keep punctuation in the right place?

What I tried

public void rev2(String str) {
    String[] arrStr = str.split(" ");
    for (int i = arrStr.length - 1; i >= 0; i--) {
        if (!arrStr[i].contains(".")) {
            System.out.print(arrStr[i] + " ");
        }
    }
}

public static void main(String[] args) {
    Test t = new Test();
    t.rev2("My name is Bob.");
}

The code above does not work as expected. I probably can convert each string to char and use Character.isAlphabet() or may be use pattern?

I could use some ideas. Thanks in advance for your time and help.

Here is a solution that works within the constraints of the question (some of which are assumed):

public void rev2(String str) {
    String[] arrStr = str.split(" ");
    for (int i = arrStr.length - 1; i >= 0; i--) {
        boolean punct = i <= 0 || arrStr[i - 1].contains(".");
        if (!arrStr[i].contains(".")) {
            System.out.print(arrStr[i]);
        } else {
            System.out.print(arrStr[i].substring(0, arrStr[i].length() - 1));
        }
        System.out.print((punct ? ". " : " "));
    }
}

public static void main(String[] args) {
    Tester t = new Tester();
    t.rev2("My name is Bob. I am happy.");
}

Explanation:

The boolean punct looks ahead to see if the next element contains a ".". If so, we are on a sentence boundry and so added a. after the current word. If not, we just put a space. We also add a "." if we are on the last element in the array.

Output: happy am I. Bob is name My.

If all you want to do regarding punctuation is keep the period at the end of the sentence, you can print the words followed by a space or by the period depending on whether they are the first word or not, and you can remove the period from the last word by calling substring() . Something like this:

public class Test {
    public void rev2(String str) {
        String[] arrStr = str.split(" ");
        for (int i = arrStr.length - 1; i >= 0; i--) {
            if (!arrStr[i].contains(".")) {
                System.out.print(arrStr[i] + (i == 0 ? "." : " "));
            } else {
                System.out.print(arrStr[i].substring(0, arrStr[i].length() - 1) + " ");
            }
        }
    }

    public static void main(String[] args) {
        Test t = new Test();
        t.rev2("My name is Bob.");
    }
}

Output: Bob is name My.

If you want a less verbose code:

var list = Arrays.asList("My name is Bob".split(" "));
Collections.reverse(list);
list.stream().map(str -> str.concat(" ")).forEach(System.out::print);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM