How to remove extra spaces and newlines in a line?

I have a string variable s that looks like a combination of passes. For instance,

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 need to make this 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.

In addition, additional spaces between words must be removed (or between "." And the first line of the word), converted to one space and any number of spaces before ",", ".". or ';' must be deleted.

I am new to java. Can someone tell me how to do this?

+4
source share
6 answers

Try the following: (@Criti method)

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

    s = s.replaceAll("\\s*\\.\\s*\n\\s*", ". ");
    s = s.replaceAll("\\s*,\\s*", ", ");
    s = s.replaceAll("\\s*;\\s*", "; ");
    System.out.println(s);

Conclusion:

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.
+2
source

One way is to parse the character of the String variable by character. for instance

StringBuilder sb = new StringBuilder();
String toBeParse = "...";
for (int i = 0; i < toBeParse.length(); i++) {
    if (toBeParse.charAt(i) == condition) {
        sb.append(toBeParse.charAt(i));
    }
}
String result = sb.toString();

:

toBeParse.replaceAll(yourRegexString, replacement);
0

str = str.replaceAll("\\.\\s+(\\w)", ". $1");
0

Apache Commons Lang - StringUtils ( ) . , StringUtils , , : StringUtils.normalizeSpace(String str)

API:

, (String), , .

0

string.replaceAll("\n", "").replaceAll("\\s+", " ")

0

Regexs - . , Google Guava CharMatcher

CharMatcher.WHITESPACE.collapseFrom( "Hello There\nMy name - Fred", ''))

This converts a space into one space, and collapses several sequences of spaces into one sequence.

0
source

All Articles