英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论