Strings are an integral part of any programming language and Java is no exception.
Java provides multiple methods to manipulate strings and splitting a string is one of the most commonly used operations.
In this tutorial, we will learn how to split a string in Java and the different methods available to do so.
What is Splitting a String?
Splitting a string refers to breaking down a string into smaller sub-strings based on a specific delimiter or separator.
The process of splitting a string is useful in various scenarios, such as when you want to extract data from a string, process strings in a loop, or store string values in an array.
Methods to Split a String in Java
There are multiple ways to split a string in Java, and we will cover the most commonly used methods in this post.
Using the split() Method:
The split() method is the most widely used method for splitting a string in Java.
It is a method of the java.lang.String class and takes the delimiter as its argument. It returns an array of strings, which represents the sub-strings.
Syntax:
String[] result = string.split(delimiter);
Example:
String s = "hello,world,java"; String[] arr = s.split(","); for(String value: arr) { System.out.println(value); }
Output:
hello world java
Using the Substring() Method:
The substring() method is another method that can be used to split a string in Java.
However, it requires a bit more manual effort compared to the split() method.
In this method, you keep calling the substring() method until you get all the sub-strings.
Syntax:
String subString = string.substring(startIndex, endIndex);
Example:
String s = "hello,world,java"; int startIndex = 0; int endIndex = s.indexOf(","); while(endIndex != -1) { String subString = s.substring(startIndex, endIndex); System.out.println(subString); startIndex = endIndex + 1; endIndex = s.indexOf(",", startIndex); }
Output:
hello world java
Using the StringTokenizer Class
The StringTokenizer class is another option for splitting a string in Java.
It is a legacy class that is present in the java.util package.
The StringTokenizer class splits a string based on the specified delimiter and returns tokens (sub-strings) as an Enumeration.
Syntax:
StringTokenizer st = new StringTokenizer(string, delimiter);
Example:
String s = "hello,world,java"; StringTokenizer st = new StringTokenizer(s, ","); while(st.hasMoreTokens()) { System.out.println(st.nextToken()); }
Output:
hello world java
Conclusion
In conclusion, we have learned about the different methods available in Java for splitting a string.