Java:通过分隔符反转字符串

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

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.

huangapple
  • 本文由 发表于 2020年4月4日 07:54:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/61022095.html
匿名

发表评论

匿名网友

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

确定