Java:如何在反转拆分字后将分隔符读回字符串?

问题描述 投票:0回答:1

在反转拆分词后,我不确定如何重新添加定界符。

String fileContent = "def  mnop.STU";
    String delimiter = "[^a-zA-Z0-9']+";
    String[] splitWords = fileContent.split(delimiter);
    StringBuilder stringBuilder = new StringBuilder();
    for (String word : splitWords) {
        StringBuilder output = new StringBuilder(word).reverse();
        stringBuilder.append(output);
    }
    StringJoiner joiner = new StringJoiner(delimiter);
    joiner.add(stringBuilder);
    System.out.println(joiner.toString());

当前输出:fedponmUTS

所需的输出:fed ponm.UTS

java string algorithm reverse
1个回答
1
投票

不是很优雅,但是你可以做这样的事情吗?

for (String word : splitWords) 
{
    int idx = fileContent.indexOf(word, stringBuilder.length());
    String delim = fileContent.substring(stringBuilder.length(), idx);
    stringBuilder.append(delim);

    StringBuilder output = new StringBuilder(word).reverse();
    stringBuilder.append(output);
}

输出:

fed  ponm.UTS
© www.soinside.com 2019 - 2024. All rights reserved.