简体   繁体   中英

Replace extra spaces in string with a single space in Java, without regex

I want to basically to do this:

String secondString = firstString.trim().replaceAll(" +", " ");

Or replace all the multiple spaces in my string, with just a single space. However, is it possibly to do this without regex like I am doing here?

Thanks!

However, is it possibly to do this without regex like I am doing here?

Yes . The regular expression is clear and easy to read, so I would probably use that; but you could use a nested loop, a StringBuilder and Character.isWhitespace(char) like

StringBuilder sb = new StringBuilder();
for (int i = 0; i < firstString.length(); i++) {
    sb.append(firstString.charAt(i));
    if (Character.isWhitespace(firstString.charAt(i))) {
        // The current character is white space, skip characters until 
        // the next character is not.
        while (i + 1 < firstString.length() 
                    && Character.isWhitespace(firstString.charAt(i + 1))) {
            i++;
        }
    }
}
String secondString = sb.toString();

Note: This is a rare example of a nested loop that is O(N); the inner loop modifies the same counter as the outer loop.

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