How to split a string with any whitespace chars as delimiters in java

How to split a string with any whitespace chars as delimiters in java

To split a string with any whitespace characters as delimiters in Java, you can use the split method of the String class with a regular expression pattern that matches one or more whitespace characters. Here's how you can do it:

public class SplitStringWithWhitespace { public static void main(String[] args) { String inputString = "Hello World\tThis\nis\ra test"; // Split the inputString using one or more whitespace characters as delimiters String[] parts = inputString.split("\\s+"); // Print the resulting parts for (String part : parts) { System.out.println(part); } } } 

In the code above:

  • \\s+ is the regular expression pattern that matches one or more whitespace characters. The \\ is used to escape the backslash because it's a special character in regular expressions, and s+ means one or more whitespace characters (spaces, tabs, newlines, or carriage returns).

  • inputString.split("\\s+") splits the inputString using the regular expression pattern as the delimiter, resulting in an array of substrings containing non-whitespace text.

  • The for loop then iterates through the resulting parts array and prints each part on a separate line.

When you run this code, it will split the input string using any whitespace characters as delimiters, including spaces, tabs, newlines, and carriage returns, producing the following output:

Hello World This is a test 

More Tags

resnet postfix-notation laravel-echo ef-database-first snackbar subreport interface-builder masm diff case-sensitive

More Java Questions

More Pregnancy Calculators

More Fitness Calculators

More Other animals Calculators

More Fitness-Health Calculators