Removing whitespace from strings in Java

前端 未结 30 1876
一个人的身影
一个人的身影 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:44

    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

提交回复
热议问题