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 split large excel file into multiple smaller files? - April 15, 2023
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023