Prior to Java 1.4 we use java.util.StringTokenizer
class to split a tokenized string, for example a comma separated string. Starting from Java 1.4 and later the java.lang.String
class introduce a String.split(String regex)
method that simplify this process.
Below is a code snippet how to do it.
package org.kodejava.lang;
import java.util.Arrays;
public class StringSplit {
public static void main(String[] args) {
String data = "1,Diego Maradona,Footballer,Argentina";
String[] items = data.split(",");
// Iterates the array to print it out.
for (String item : items) {
System.out.println("item = " + item);
}
// Or simply use Arrays.toString() when print it out.
System.out.println("item = " + Arrays.toString(items));
}
}
The result of the code snippet:
item = 1
item = Diego Maradona
item = Footballer
item = Argentina
item = [1, Diego Maradona, Footballer, Argentina]
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024