简体   繁体   中英

How to remove blank lines in middle of a string Android

String Address[] = mSelectedaddress.split("\\|");
address.setText(
                Address[1] + "\n"
                        + Address[2] + "\n"
                        + Address[3] + "\n"
                        + Address[4]);

Actual Output:

Address 1
Address 2
                => Blank line           
City

Wanted Output:

Address 1
Address 2         
City

If u can see my above code there are some scenario where Address[positon] may return blank text that time how can i remove that line if it is blank.

String adjusted = adress.replaceAll("(?m)^[ \t]*\r?\n", "");

When you build your string, check to see if the string is empty before you add it.

StringBuilder builder = new StringBuilder();
for(int it = 0; i < Address.length; i++) {
    if(Address[i] != "")
        builder.append(Address[i]);
    }
    address.setText(builder.toString());
}

The simplest thing I can think of that should do the trick most of the time:

mSelectedaddress.replaceAll("[\\|\\s]+", "|").split("\\|");

This will remove multiple |'s (with or without spaces) in a row. Those are the cause of your empty lines.

Example:

"a|b|c|d|e||g" -> works
"a|b|c|d|e|   |g" -> works
"a|b|c|d|e|||g" -> works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM