What is the method in Java to remove white spaces from a string?
In Java, you can use the following method to remove spaces from a string:
- remove extra spaces from both the beginning and end of a string
String str = " hello world ";
String trimmedStr = str.trim();
System.out.println(trimmedStr); // 输出: "hello world"
- Replace all occurrences.
String str = " hello world ";
String noSpaceStr = str.replaceAll("\\s", "");
System.out.println(noSpaceStr); // 输出: "helloworld"
-
substitute
String str = " hello world ";
String noSpaceStr = str.replace(" ", "");
System.out.println(noSpaceStr); // 输出: "helloworld"
These methods can be selected based on specific needs to choose which way to remove spaces.