How to split a string in Java?

How to split a string in Java?

In Java, you can split a string into an array of substrings using the split() method of the String class. The split() method takes a regular expression (regex) as its argument and returns an array of substrings based on the regex pattern. Here's how to use it:

public class StringSplitExample {
    public static void main(String[] args) {
        String input = "apple,banana,cherry,date";
        
        // Split the input string by comma ","
        String[] parts = input.split(",");
        
        // Loop through the array of substrings and print them
        for (String part : parts) {
            System.out.println(part);
        }
    }
}

In this example:

  1. We have a string input containing comma-separated values.

  2. We use the split(",") method to split the string into an array of substrings based on the comma , delimiter.

  3. The resulting array parts contains the substrings: "apple", "banana", "cherry", and "date".

  4. We then loop through the array and print each substring.

You can specify any regular expression as the argument to split() to split the string based on a custom delimiter or pattern. For example, to split by whitespace or multiple spaces, you can use split("\\s+"), where \\s+ is a regex pattern that matches one or more whitespace characters.

Here's an example of splitting by whitespace:

String input = "apple   banana  cherry date";
String[] parts = input.split("\\s+");

for (String part : parts) {
    System.out.println(part);
}

This would split the string into "apple", "banana", "cherry", and "date" with multiple spaces as the delimiter.


More Tags

pywin32 selectlist implicit jframe command-prompt quartz-scheduler webdriver iequalitycomparer nginfinitescroll discord.js

More Java Questions

More Entertainment Anecdotes Calculators

More Math Calculators

More Biochemistry Calculators

More Physical chemistry Calculators