Removing whitespace from strings in Java

前端 未结 30 1874
一个人的身影
一个人的身影 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条回答
  • 2020-11-22 05:36
    mysz = mysz.replace(" ","");
    

    First with space, second without space.

    Then it is done.

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

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

    "myString".replace(Regex("\\s+"), "")
    
    0 讨论(0)
  • 2020-11-22 05:38

    If you prefer utility classes to regexes, there is a method trimAllWhitespace(String) in StringUtils in the Spring Framework.

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

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

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

    White space can remove using isWhitespace function from Character Class.

    public static void main(String[] args) {
        String withSpace = "Remove white space from line";
        StringBuilder removeSpace = new StringBuilder();
    
        for (int i = 0; i<withSpace.length();i++){
            if(!Character.isWhitespace(withSpace.charAt(i))){
                removeSpace=removeSpace.append(withSpace.charAt(i));
            }
        }
        System.out.println(removeSpace);
    }
    
    0 讨论(0)
  • 2020-11-22 05:39
    public static void main(String[] args) {        
        String s = "name=john age=13 year=2001";
        String t = s.replaceAll(" ", "");
        System.out.println("s: " + s + ", t: " + t);
    }
    
    Output:
    s: name=john age=13 year=2001, t: name=johnage=13year=2001
    
    0 讨论(0)
提交回复
热议问题