In this guide, we will discuss how to split a string by comma (,). You can use Java String split() method to split a given string.
Example 1: Split String by Comma
Here, we have a comma separated string. To split this string into substring using comma as delimiter, we are passing the ,
symbol in the split() method.
public class JavaExample { public static void main(String[] args) { String str = "This,is,a,test,string"; //passing comma as delimiter String[] strArray = str.split(","); //displaying string array elements for(String s: strArray){ System.out.println(s); } } }
Output:
Example 2: Limit the number of substrings after split
In the above example, we are getting all the substrings after split operation. Let’s see how can we limit the number of substrings we get.
To do this, we will use the following variation of the string method. This allows us to pass the integer number along with the delimiter into the split method.
public String split(String regex, int limit)
Let’s see an example to understand how this limit affect the output of the program:
public class JavaExample { public static void main(String[] args) { String str = "This,is,a,test,string "; //passing comma as delimiter and a limit of 3 String[] strArray = str.split(",", 3); for(String s: strArray){ System.out.println(s); } } }
Output: As you can see, the number of substrings returned by the split method is limited to 3, this is because we passed the limit as 3.
Example 3: Split User entered String by comma delimiter
In the above examples, the string is initialized in the program. In this program, the string is entered by user, which we will capture using Scanner class.
import java.util.Scanner; public class JavaExample { public static void main(String[] args) { String str; //getting the string from user System.out.println("Enter a string that contains commas: "); Scanner scan = new Scanner(System.in); str = scan.nextLine(); String[] strArray = str.split(","); System.out.println("Split result: "); for(String s: strArray){ System.out.println(s); } } }
Output: User entered a string that contains commas, the program split this string using comma as delimiter and returned a string array. The elements of this string array are displayed using enhanced for loop.