Java: 如何在拆分单词并反转后将分隔符重新添加到字符串中?

huangapple go评论152阅读模式
英文:

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

问题

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);
for (String reversedWord : splitWords) {
    joiner.add(new StringBuilder(reversedWord).reverse());
}
System.out.println(joiner.toString());
Current output: fedponmUTS
Desired output: fed  ponm.UTS
英文:

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

答案1

得分: 2

这不是非常优雅的代码,但你能否像这样做?

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
英文:

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

huangapple
  • 本文由 发表于 2020年4月6日 13:12:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/61053304.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定