如何交换字符串中特定单词的顺序?

js4nwp54  于 2021-08-20  发布在  Java
关注(0)|答案(3)|浏览(276)

我有一个字符串:

String test = "This is a test string of many words and more";

此外,我还有一个需要交换的独特单词列表:

List<String> words = Arrays.asList("is", "test", "words", "more");

该列表包含按正确顺序从原始字符串中提取的单词。颠倒顺序的字数是变化的。结果必须是这样的:列表中的所有单词都被反转并放入原始字符串中

"This more a words string of many test and is"

按空间分割将不起作用,因为这是特定问题的一般解决方案。

jhdbpxl9

jhdbpxl91#

试试这个:

public static void main(String[] args) {

    String test = "This is a test string of many words and more";
    List<String> words = Arrays.asList("is", "test", "words", "more");
    int size = words.size();
    for (int i = 0; i < size / 2; i++) {
        String firstWord = " "+words.get(i)+" ";
        String secondWord = " "+words.get(size - 1 - i)+" ";
        String temp = "####";
        test = test.replace(firstWord, temp);
        test = test.replace(secondWord, firstWord);
        test = test.replace(temp, secondWord);
    }
    System.out.println(test);
}
a0zr77ik

a0zr77ik2#

干得好:

String test = "This is a test string of many words and more";
    List<String> words = Arrays.asList("is", "test", "words", "more");

    String split[] = test.split(" ");

    int listIndex = 0;
    int lastListIndex = words.size() - 1;
    int lastIndex = split.length - 1;

    for (int i = 0; i < split.length; i++) {
        String word = split[i];

        if (word.equals(words.get(listIndex))) {
            for (int h = lastIndex; h >= 0; h--) {
                String word1 = split[h];
                if (word1.equals(words.get(lastListIndex))) {
                    split[i] = word1;
                    split[h] = word;
                    lastListIndex--;
                    listIndex++;
                    break;
                }
            }
            if (listIndex == lastListIndex) break;
        }

    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < split.length; i++) {
        String str = split[i];
        if (i == split.length - 1) sb.append(str);
        else sb.append(str).append(" ");
    }

    String output = sb.toString();

    System.out.println(output);

我已经测试过了。如果你需要解释,请在评论中提问。

laximzn5

laximzn53#

这是另一种方法

private static void swapWords() {
    String test = "This is a test string of many words and more";

    List<String> words = Arrays.asList("is", "test", "words", "more");
    Map<String, String> mappings = new HashMap<>();
    for (int i = 0; i < words.size(); i++) {
        mappings.put(words.get(i), words.get(words.size() - 1 - i));
    }

    var output = Arrays.stream(test.split(" "))
            .map(word -> mappings.getOrDefault(word, word))
            .collect(Collectors.joining(" "));

    System.out.println(output);
}

相关问题