如何在Java中翻转两个单词

时间:2019-05-09 16:37:56

标签: java arrays string arraylist

如何用类似Java的句子翻转两个单词

输入:“嗨,你今天简怎么样?

输出:“您今天过得怎么样简?”

我尝试了什么:

NDK

我得到的输出: “您今天好吗”

3 个答案:

答案 0 :(得分:2)

正如您所要求的那样,仅使用一个循环而无需大量使用正则表达式,这是使用Collections.swap的另一种解决方案:

String s = "hi how are you doing today jane";
List<String> splitted = new ArrayList<>(List.of(s.split("\\s+")));

for(int i = 0; i < splitted.size() - 1; i += 2)
    Collections.swap(splitted, i, i + 1);
s = String.join(" ", splitted);
System.out.println(s);

输出:

  

你好,你今天在做简吗

答案 1 :(得分:1)

由于您正在使用带有正则表达式的split(),因此看来使用正则表达式是有效的解决方案,因此请使用它:

replaceAll("(\\w+)(\\W+)(\\w+)", "$3$2$1")

说明

(\\w+)   Match first word, and capture it as group 1
(\\W+)   Match the characters between the 2 words, and capture them as group 2
(\\w+)   Match second word, and capture it as group 3
$3$2$1   Replace the above with the 3 groups in reverse order

示例

System.out.println("hi how are you doing today jane".replaceAll("(\\w+)(\\W+)(\\w+)", "$3$2$1"));

输出

how hi you are today doing jane

注意:由于您的代码使用split("\\s+"),因此您对“单词”的定义是一系列非空白字符。要使用单词的定义,请将正则表达式更改为:

replaceAll("(\\S+)(\\s+)(\\S+)", "$3$2$1")

答案 2 :(得分:0)

如果您想使用老式的fori循环和bufor / temp值解决方案,请按以下步骤操作:

public static void main(String[] args) {
    String s = "hi how are you doing today jane";
    String flip = flip(s);
    System.out.println(flip);
}

private static String flip(String sentence) {

    List<String> words = Arrays.asList(sentence.split("\\s+"));

    for (int i = 0; i < words.size(); i += 2) {
        if (i + 1 < words.size()) {
            String tmp = words.get(i + 1);
            words.set(i + 1, words.get(i));
            words.set(i, tmp);
        }
    }
    return words.stream().map(String::toString).collect(Collectors.joining(" "));
}

但是Pauls solultion更好,因为它是Java,而且我们不再处在石器时代:)