How to reverse words in a string but keep punctuation in the right place? [duplicate]

南笙酒味 提交于 2021-02-10 04:22:16

问题


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


回答1:


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() + '"');



回答2:


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 :/.




回答3:


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


来源:https://stackoverflow.com/questions/33899575/how-to-reverse-words-in-a-string-but-keep-punctuation-in-the-right-place

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!