This post shows how you can split a String in Java using split() method. String you need to split may be delimited using pipe, tab or spaces so let’s see how to use split() method to split such delimited data strings in Java. Note that if you are using any special symbol with in the regular expression then you do need to escape it using escape character (\).
Splitting String delimited using pipe(|) symbol – Java code
public class SplitString { public static void main(String[] args) { String str = "A001|BOA|Ronda|5000"; String[] data = str.split("\\|"); System.out.println("Name- " + data[2]); } }
Output
Name- Ronda
Splitting data in Java delimited using tab (\t)
public class SplitString { public static void main(String[] args) { String str = "A001 BOA Ronda 5000"; String[] data = str.split("\t"); System.out.println("Amount- " + data[3]); } }
Output
Amount- 5000
Splitting data delimited using spaces- Java code
public class SplitString { public static void main(String[] args) { String str = "A001 BOA Ronda 5000"; // Matches any number of spaces String[] data = str.split("\\s+"); System.out.println("Amount- " + data[3]); } }
Output
Amount- 5000
Splitting data delimited using single space
public class SplitString { public static void main(String[] args) { String str = "A001 BOA Ronda 5000"; // Matches any number of spaces String[] data = str.split("\\s"); System.out.println("Name- " + data[2]); } }
Output
Name- Ronda
Related Posts
- How to Reverse a String in Java
- Java Program to Count The Frequency of Each Character in a String
- Java Program to Count Number of Words in a String
- Convert Char to String And String to Char in Java
- Java Program to Check Whether Number Prime or Not
- Display Prime Numbers in Java
- Remove Element From an Array in Java
- How to Copy a Directory in Java
That’s all for the topic How to Split a String in Java. If something is missing or you have something to share about the topic please write a comment.
You may also like