To break a string at a comma in Java, you can use the split()
method of the String
class. The split()
method splits a string into an array of substrings based on a specified delimiter.
Here is an example of how to use the split()
method to break a string at a comma:
String str = "apple,banana,cherry,date,elderberry"; String[] fruits = str.split(","); for (String fruit : fruits) { System.out.println(fruit); }
In this example, the split()
method is used to split the string str
into an array of substrings based on the delimiter ","
. The resulting array is stored in the fruits
array. Then, a for-each loop is used to iterate over the fruits
array and print each element to the console. The output will be:
apple banana cherry date elderberry
You can also use the split()
method to specify a limit on the number of substrings that are returned. For example:
String str = "apple,banana,cherry,date,elderberry"; String[] fruits = str.split(",", 3); for (String fruit : fruits) { System.out.println(fruit); }
In this example, the split()
method is used to split the string str
into an array of substrings based on the delimiter ","
, but it returns a maximum of 3 substrings. The output will be:
apple banana cherry,date,elderberry
Note that the split()
method is case sensitive, so it will only split the string at a comma and not at a COMMA. If you want to split the string at a comma or a COMMA, you can use the "(,|,)"
pattern as the delimiter.
String str = "apple,banana,cherry,date,elderberry"; String[] fruits = str.split("(,|,)"); for (String fruit : fruits) { System.out.println(fruit); }
In this example, the split()
method is used to split the string str
into an array of substrings based on the delimiter "(,|,)"
, which matches either a comma or a COMMA. The output will be the same as in the first example.