To strip spaces in a string using the split
method in Java, you can use a regular expression as the delimiter that matches one or more whitespace characters.
Here's an example of how you can do this:
String input = "This is a test string "; String[] parts = input.split("\\s+"); for (String part : parts) { System.out.println(part); }
This code will split the input string at any sequence of one or more whitespace characters, and print the resulting parts to the console. The output will be:
This is a test string
Note that the split
method will remove the delimiter characters from the resulting parts, so you don't have to worry about stripping the spaces manually.
You can also use the split
method with other delimiters by specifying the delimiter pattern in the regular expression. For example, to split the input string at any sequence of one or more whitespace characters or punctuation marks, you can use the following regular expression:
String[] parts = input.split("[\\s\\p{Punct}]+");
This will split the input string at any sequence of one or more whitespace characters or punctuation marks, and return the resulting parts.
You can refer to the Java documentation on regular expressions for more information on how to use regular expressions with the split
method.