Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove newline from string

Tags:

java

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?

like image 412
Trups Avatar asked Oct 17 '25 11:10

Trups


1 Answers

The ASCII code 0x0d is CR (Carriage Return).

When a string includes CR+LFs as line separators (e.g. on Windows) and your system uses LFs as line separators (e.g. on Unix descendants), System.getProperty("line.separator") just gives you LF. So your code removes only LFs let alone CRs.

If you just get rid of CR or LF, below may be sufficient.

response.replaceAll("[\\r\\n]", "");
like image 101
hata Avatar answered Oct 20 '25 03:10

hata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!