Java Split String by Comma

It is a very common and mostly searched program by interviewers. We can split a string based on some specific string delimiter. We mostly spit a string by comma or space. We use the split() method of the string to split.

Java Split String by Comma

The syntax of the split() method is as follows:

The split method accepts one or two parameters based on the requirement.

regex

The regex parameter defines a regular expression which is applied to the string/text.

limit

It defines the maximum number of values in the array. If the limit is 0, the method returns all the strings that match the given regex.

To learn more about the split() method, go through the following link: https://www.javatpoint.com/java-string-split

Let's take an example to understand how to split a string with the delimiter.

Suppose we have string str that is formed of words like Integer, Decimal, Float, Double and String - all separated by a comma.

Now, if we split the string by using the split() method, we will get five separate strings which are as follows:

  1. Integer
  2. Decimal
  3. Float
  4. Double
  5. String

Let's implement the code for splitting a user-given string by a comma or space:

SplitStringExample1.java

Output:

Java Split String by Comma

SplitStringExample2.java

Output:

Java Split String by Comma