Removing whitespace from strings in Java

2020-01-22 12:02发布

I have a string like this:

mysz = "name=john age=13 year=2001";

I want to remove the whitespaces in the string. I tried trim() but this removes only whitespaces before and after the whole string. I also tried replaceAll("\\W", "") but then the = also gets removed.

How can I achieve a string with:

mysz2 = "name=johnage=13year=2001"

30条回答
ゆ 、 Hurt°
2楼-- · 2020-01-22 12:05

The easiest way to do this is by using the org.apache.commons.lang3.StringUtils class of commons-lang3 library such as "commons-lang3-3.1.jar" for example.

Use the static method "StringUtils.deleteWhitespace(String str)" on your input string & it will return you a string after removing all the white spaces from it. I tried your example string "name=john age=13 year=2001" & it returned me exactly the string that you wanted - "name=johnage=13year=2001". Hope this helps.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-01-22 12:05

Separate each group of text into its own substring and then concatenate those substrings:

public Address(String street, String city, String state, String zip ) {
    this.street = street;
    this.city = city;
    // Now checking to make sure that state has no spaces...
    int position = state.indexOf(" ");
    if(position >=0) {
        //now putting state back together if it has spaces...
        state = state.substring(0, position) + state.substring(position + 1);  
    }
}
查看更多
贼婆χ
4楼-- · 2020-01-22 12:08

One way to handle String manipulations is StringUtils from Apache commons.

String withoutWhitespace = StringUtils.deleteWhitespace(whitespaces);

You can find it here. commons-lang includes lots more and is well supported.

查看更多
Viruses.
5楼-- · 2020-01-22 12:08

If you need to remove unbreakable spaces too, you can upgrade your code like this :

st.replaceAll("[\\s|\\u00A0]+", "");
查看更多
Melony?
6楼-- · 2020-01-22 12:08

You've already got the correct answer from Gursel Koca but I believe that there's a good chance that this is not what you really want to do. How about parsing the key-values instead?

import java.util.Enumeration;
import java.util.Hashtable;

class SplitIt {
  public static void main(String args[])  {

    String person = "name=john age=13 year=2001";

    for (String p : person.split("\\s")) {
      String[] keyValue = p.split("=");
      System.out.println(keyValue[0] + " = " + keyValue[1]);
    }
  }
}

output:
name = john
age = 13
year = 2001

查看更多
Viruses.
7楼-- · 2020-01-22 12:10

When using st.replaceAll("\\s+","") in Kotlin, make sure you wrap "\\s+" with Regex:

"myString".replace(Regex("\\s+"), "")
查看更多
登录 后发表回答