'How to remove newline from string

My application flow is like i need to create a fixed length message and send it to end consumer over mqs.

AAA
BBB
CCC
DDD

Needs to be converted to AAABBBCCCDDD and send to end application over mqs for this i am using below code

String response = "AAA
BBB
CCC
DDD";
response.replaceAll(System.getProperty("line.separator"), "");
response = AAABBBCCCDDD

Everything is good so far, but when the message reach to end system they are complaining about a space after each line and when checked via hex it looks like a 0D character is getting inserted at place of next line

AAA BBB CCC DDD -> This is how they are received

AAA0DBBB0DCCC0DDDD -> Hex enabled Hex’0D’ (I think it’s more like delimiter, EOL or something)

Can someone suggest how can i get rid of these characters which are getting added?



Solution 1:[1]

Use the any linebreak regex \R:

response.replaceAll("\\R", "");

According to the documentation:

\R Any Unicode linebreak sequence, is equivalent to
\u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]

Solution 2:[2]

If you want to remove the whitespace separators in your input, retaining all non whitespace characters, then a simple replace all should suffice:

String response = "AAA\nBBB\nCCC\nDDD";
String output = response.replaceAll("\\s+", "");
System.out.println(output); // AAABBBCCCDDD

Solution 3:[3]

responseTransactions.replaceAll("\r?\n", ""); this worked for me and the end systems have also confirmed that now they are not receiving any spaces or 0D in the message.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Tim Biegeleisen
Solution 3 Trups