Removing whitespace from strings in Java

前端 未结 30 1873
一个人的身影
一个人的身影 2020-11-22 05:01

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()

相关标签:
30条回答
  • private String generateAttachName(String fileName, String searchOn, String char1) {
        return fileName.replaceAll(searchOn, char1);
    }
    
    
    String fileName= generateAttachName("Hello My Mom","\\s","");
    
    0 讨论(0)
  • 2020-11-22 05:32
    String a="string with                multi spaces ";
    //or this 
    String b= a.replaceAll("\\s+"," ");
    String c= a.replace("    "," ").replace("   "," ").replace("  "," ").replace("   "," ").replace("  "," ");
    

    //it work fine with any spaces *don't forget space in sting b

    0 讨论(0)
  • 2020-11-22 05:33

    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.

    0 讨论(0)
  • 2020-11-22 05:33

    \W means "non word character". The pattern for whitespace characters is \s. This is well documented in the Pattern javadoc.

    0 讨论(0)
  • 2020-11-22 05:35

    You should use

    s.replaceAll("\\s+", "");
    

    instead of:

    s.replaceAll("\\s", "");
    

    This way, it will work with more than one spaces between each string. The + sign in the above regex means "one or more \s"

    --\s = Anything that is a space character (including space, tab characters etc). Why do we need s+ here?

    0 讨论(0)
  • 2020-11-22 05:35

    In java we can do following operation:

    String pattern="[\\s]";
    String replace="";
    part="name=john age=13 year=2001";
    Pattern p=Pattern.compile(pattern);
    Matcher m=p.matcher(part);
    part=m.replaceAll(replace);
    System.out.println(part);
    

    for this you need to import following packages to your program:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    

    i hope it will help you.

    0 讨论(0)
提交回复
热议问题