Java - Split a String by Character
Last Updated :
09 Dec, 2024
In Java, we can use the split() method from the String class to split a string by character, which simplifies this process by taking a regular expression (regex) as its argument. It returns an array of strings, allowing us to easily manipulate the parts of the original string.
Example: The split() method divides a string into substrings based on a given character or regex.
Java
// Java program to split a string using
// the split() method
public class SplitString {
public static void main(String[] args) {
String s = "Java,C,Python";
// Split the string by comma
String[] p = s.split(",");
for (String part : p) {
System.out.println(part);
}
}
}
Explanation: The above program uses split(",") to divide the string into substrings wherever a comma appears. The parts are printed one by one.
Other Methods to Split a String by Character
1. Using StringBuilder
For more control over the splitting process, we can use StringBuilder to manually build parts of the string.
Java
// Java program to split a string
// using StringBuilder
public class SplitString {
public static void main(String[] args) {
String s = "Java,C,Python";
StringBuilder sb = new StringBuilder();
for (char ch : s.toCharArray()) {
// Split by character ','
if (ch == ',') {
System.out.println(sb.toString());
sb.setLength(0); // Reset the builder
} else {
sb.append(ch); // Append the current character
}
}
// Print the last part
System.out.println(sb.toString());
}
}
Explanation: In the above example, the StringBuilder approach offers fine-grained control over the splitting process. Each part is manually constructed and printed.
2. Using StringTokenizer
(Legacy Approach)
The StringTokenizer class provides another way to split strings by a specific delimiter. This approach is considered outdated.
Java
// Java program to split a string
// using StringTokenizer
import java.util.StringTokenizer;
public class SplitString {
public static void main(String[] args) {
String s = "Java,C,Python";
// Delimiter is ','
StringTokenizer t = new StringTokenizer(s, ",");
// Print each token
while (t.hasMoreTokens()) {
System.out.println(t.nextToken());
}
}
}
Explanation: In the above example, the StringTokenizer splits the string into tokens based on the specified delimiter and provides methods like nextToken() to retrieve them.
3. Using Java Streams (Java 8+)
Java 8 introduced streams that offers a functional approach for splitting and processing strings.
Java
// Java program to split a string
// using Streams
import java.util.Arrays;
public class SplitString {
public static void main(String[] args) {
String s = "Java,C,Python";
// Use Streams to split and print the string
Arrays.stream(s.split(","))
.forEach(System.out::println);
}
}
Explanation: In the above example, the split() method creates an array, which is then converted into a stream. The forEach method processes and prints each substring.
When to Use Which Method
- split() Method: Splits a string into substrings based on a regex and returns an array.
- StringBuilder: Manually constructs parts of the string while splitting by a character.
- StringTokenizer: Legacy approach to split strings using a delimiter.
- Java Streams: Functional approach to split strings and process them in Java 8+.
Similar Reads
Convert a String to a List of Characters in Java In Java, to convert a string into a list of characters, we can use several methods depending on the requirements. In this article, we will learn how to convert a string to a list of characters in Java.Example:In this example, we will use the toCharArray() method to convert a String into a character
3 min read
Java String charAt() Method String charAt() method in Java returns the character at the specified index in a string. The Index of the first character in a string is 0, the second character is 1, and so on. The index value should lie between 0 and length() - 1.If the index value is greater than or equal to the string length or
2 min read
Java Program to Get a Character from a String Given a String str, the task is to get a specific character from that String at a specific index. Examples:Input: str = "Geeks", index = 2Output: eInput: str = "GeeksForGeeks", index = 5Output: F Below are various ways to do so: Using String.charAt() method: Get the string and the indexGet the speci
5 min read
Convert List of Characters to String in Java Given a list of characters. In this article, we will write a Java program to convert the given list to a string. Example of List-to-String ConversionInput : list = {'g', 'e', 'e', 'k', 's'} Output : "geeks" Input : list = {'a', 'b', 'c'} Output : "abc" Strings - Strings in Java are objects that are
4 min read
Swapping Pairs of Characters in a String in Java Given string str, the task is to write a Java program to swap the pairs of characters of a string. If the string contains an odd number of characters then the last character remains as it is. Examples: Input: str = âJavaâOutput: aJav Explanation: The given string contains even number of characters.
3 min read