You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调换字符串中指定单词的顺序,无需采用按空格拆分的方式

单词反转替换解决方案

实现思路

因为要求不能拆分字符串,我们采用位置匹配+倒序替换的方案实现需求:

  • 首先将待替换的单词列表反转,得到最终要替换的目标序列
  • 遍历原始待替换单词列表,在原字符串中匹配每个单词的完整位置(避免子串误匹配),按出现顺序存储所有匹配的起止索引
  • 从后往前依次替换对应位置的单词,倒序操作可以避免先修改前半段字符串导致后续匹配位置偏移的问题

代码实现

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// Java21以下版本需要额外导入 import java.util.Collections;

public class ReplaceTest {
    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");
        System.out.println(reverseReplace(test, words));
    }

    public static String reverseReplace(String original, List<String> targetWords) {
        // 反转得到替换用的单词序列,Java21以下版本替换为下方注释的代码
        List<String> reversedWords = targetWords.reversed();
        /*
        List<String> reversedWords = new ArrayList<>(targetWords);
        Collections.reverse(reversedWords);
        */
        List<int[]> matchPos = new ArrayList<>();

        // 收集所有目标单词的匹配位置
        for (String word : targetWords) {
            // 用单词边界保证匹配完整单词,Pattern.quote规避特殊字符影响
            Matcher matcher = Pattern.compile("\\b" + Pattern.quote(word) + "\\b")
                    .matcher(original);
            if (matcher.find()) {
                matchPos.add(new int[]{matcher.start(), matcher.end()});
            }
        }

        // 倒序替换避免位置偏移
        StringBuilder sb = new StringBuilder(original);
        for (int i = matchPos.size() - 1; i >= 0; i--) {
            int[] pos = matchPos.get(i);
            sb.replace(pos[0], pos[1], reversedWords.get(i));
        }
        return sb.toString();
    }
}

输出结果

This more a words string of many test and is

方案说明

  • 全程没有拆分字符串,完全基于原字符串的位置匹配操作,符合要求
  • 支持任意数量的待替换单词,只要保证输入的目标单词列表是按原字符串出现顺序排列且单词唯一即可
  • 加入了正则特殊字符转义和单词边界匹配,适配更复杂的输入场景,通用性更强

内容的提问来源于stack exchange,提问作者Audoryosa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 15:51:02