简体   繁体   中英

Java: How to readd delimiter back to string after reversing split word?

After I reverse the split words, I am unsure on how to re add the delimiters.

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

Current output: fedponmUTS

Desired output: fed ponm.UTS

It's not very elegant, but could you do something like this?

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

Output:

fed  ponm.UTS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM