英文:
Java: Reverse string via a delimiter
问题
String fileContent = "Abc.134dsq";
String delimiter = ".";
fileContent = fileContent.replace(delimiter, "-");
String[] splitWords = fileContent.split("-");
StringBuilder stringBuilder = new StringBuilder();
for (String word : splitWords) {
StringBuilder output = new StringBuilder(word).reverse();
stringBuilder.append(output);
}
System.out.println(stringBuilder.toString());
英文:
I am trying to reverse the characters in a string separated by a delimiter I provide.
Input: string: "Abc.134dsq"
, delimiter: "."
Desired Output: cbA.qsd431
My attempt:
String fileContent = "Abc.134dsq";
String delimiter = ".";
fileContent = fileContent.replace(delimiter, "-");
String[] splitWords = fileContent.split("-");
StringBuilder stringBuilder = new StringBuilder();
for (String word : splitWords) {
StringBuilder output = new StringBuilder(word).reverse();
stringBuilder.append(output);
}
System.out.println(stringBuilder.toString());
答案1
得分: 1
试试这个:
System.out.println(Arrays
.stream("Abc.134dsq".split("\\.", -1))
.map(StringBuilder::new)
.map(StringBuilder::reverse)
.collect(Collectors.joining(".")));
查看实时演示。
这处理了评论中提到的“保留尾部点”的情况。实时演示也展示了这个方面。
足够的时间已经过去,你的作业截止日期已经过去了,所以我想向你展示这个一行代码。
英文:
Try this:
System.out.println(Arrays
.stream("Abc.134dsq".split("\\.", -1))
.map(StringBuilder::new)
.map(StringBuilder::reverse)
.collect(Collectors.joining(".")));
See live demo.
This handles the “preserving the trailing dot” scenarios mentioned in the comments. Live demo shows this aspect too.
Enough time has passed that your homework deadline has passed, so I thought I’d show you this one-liner.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论