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:

  1. 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"
  1. Replace all occurrences.
String str = "  hello world  ";
String noSpaceStr = str.replaceAll("\\s", "");
System.out.println(noSpaceStr); // 输出: "helloworld"
  1. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *