sarav
sarav

Reputation: 47

How to remove the last character from a multiline string?

Example: Consider a String like below:

String a="This line1 has a,b,c,\nThis line2 has d,e,f, \nThis line3 has g,h,i";
System.out.println(a);

Output:

This line1 has a,b,c,                 
This line2 has d,e,f,                        
This line3 has g,h,i

As this is a multiline string, How will I be able to remove last occurring comma of each line here from the output & print an output like below below mentioned?

This line1 has a,b,c                
This line2 has d,e,f                        
This line3 has g,h,i

Upvotes: 3

Views: 690

Answers (1)

assylias
assylias

Reputation: 328568

You could use a regex:

String output = a.replaceAll(",\\s*\n", "\n");

It will replace any sequence of a comma, 0 or more spaces and a newline with just a newline character.

Upvotes: 10

Related Questions