Home >Java >javaTutorial >How Can I Correctly Split a Java String by Spaces, Including Multiple Spaces and Other Whitespace Characters?

How Can I Correctly Split a Java String by Spaces, Including Multiple Spaces and Other Whitespace Characters?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 20:58:17488browse

How Can I Correctly Split a Java String by Spaces, Including Multiple Spaces and Other Whitespace Characters?

Splitting a String by Spaces in Java

Splitting a string by spaces is a common task in programming. The Java String class provides a split() method that can be used to split a string into an array of substrings.

However, sometimes you may encounter issues when using the split() method. For example, the following code does not seem to work:

String str = "Hello I'm your String";
String[] splited = str.split(" ");

This code will not split the string because the default delimiter used by the split() method is a single space character. If your string contains spaces that are separated by other characters, such as punctuation marks, the split() method will not split the string correctly.

To solve this issue, you can use the following regular expression:

str = "Hello I'm your String";
String[] splited = str.split("\s+");

This regular expression will match any number of consecutive whitespace characters, including spaces, tabs, and newlines. This will cause the split() method to split the string into tokens based on any sequence of whitespace characters.

Using this regular expression, you can successfully split a string by spaces, even if the spaces are separated by other characters.

The above is the detailed content of How Can I Correctly Split a Java String by Spaces, Including Multiple Spaces and Other Whitespace Characters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn