Chris Smith
Chris Smith

Reputation: 409

JAVA: Delimiter removed when reversing a string

How can I include the delimiter when reversing my string via code below?

Pattern.compile(Pattern.quote("."))
       .splitAsStream("BCTVW.")
       .map(s->new StringBuilder(s).reverse())
       .collect(Collectors.joining("."))

Current output: WVTCB.
Desired output: .WVTCB

The delimiter is missing from the desired output.

Upvotes: 1

Views: 89

Answers (2)

Pshemo
Pshemo

Reputation: 124265

Pattern(regex).splitAsStream(data) has similar functionality as data.split(regex) so it also removes trailing empty strings created as result of splitting.
For instance "a,b,".split(",") would NOT result in ["a","b",""] but ["a","b"] because empty strings at the end of array would be removed.

Most crucial difference between Pattern#splitAsStream and String#split is that String#split(regex) method has overloaded version String#split(regex, limit) where limit depending on value affects its result.

If limit is

  • positive it sets maximal amount of elements in resulting array like "a,b,c,d".split(",", 3) would result in ["a", "b", "c,d"].
  • 0 it causes removal of trailing empty strings (split(regex,0) is same as split(regex)
  • negative - prevents split from removing trailing empty strings - this is what you are after.

So don't use Pattern#splitAsStream but instead String#split method like you tried in your previous question:

quotation in case previous question would be removed

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

Things you need to correct there:

  1. DONT replace delimiter in your string to - to split on - because your string may contain its own -. For instance "A.B-C" after replacing . to - will become A-B-C which will result in unwanted splitting B-C.

    Instead split using Pattern.quote(delimiter) - like you did in example provided in current question.

  2. Use split with negative limit parameter to prevent removing trailing empty strings (something like fileContent.split(Pattern(delimiter), -1))

  3. You are not adding delimiters back to resulting string. Easy solution would be using StringJoiner joiner = new StringJoiner(delimiter); joiner.add(reversedElement) instead of StringBuilder because joiner.add will also handle adding delimiter between elements we want to join.

Upvotes: 1

adnan_e
adnan_e

Reputation: 1799

You can use non-capturing groups, e.g. lookahead.

Pattern.compile("(?<=\\.)")
             .splitAsStream("BCTVW.")
             .map(s->new StringBuilder(s).reverse())
             .collect(Collectors.joining("."));

Upvotes: 1

Related Questions