Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove extra spaces and new lines in a string?

I have a string variable s which is like a combination of passages. For example,

Passages provides funeral and burial products.

Our products are meant to align with your values and bring you comfort.

Our products allow you to offer personalization , flexibility and innovative choices, helping you provide services to a wider range of customers.

I have to make that string variable of this form:

Passages provides funeral and burial products. Our products are meant to align with your values and bring you comfort. Our products allow you to offer personalization, flexibility and innovative choices, helping you provide services to a wider range of customers.

Plus, extra spaces between words are to be removed(or between a '.' and the first line of the word) an converted to a single space and any number of spaces before ',','.' or ';' is to be removed.

I am a newbie in java. Can anybody tell me how can it be done?

like image 477
Sam Sonnell Avatar asked Feb 09 '23 17:02

Sam Sonnell


1 Answers

I'm a big fan of the Apache Commons Lang library - the StringUtils class (with its null-safe functions) has saved me countless hours over the years. Not surprisingly, StringUtils has a function that does what you're looking for: StringUtils.normalizeSpace(String str)

From the API:

The function returns the argument string with whitespace normalized by using trim(String) to remove leading and trailing whitespace and then replacing sequences of whitespace characters by a single space.

like image 152
Paul Avatar answered Feb 12 '23 10:02

Paul