Undoubtedly String class from java.lang package is the most widely used class in Java programming language. If you are creating a school or college project or even an enterprise-level project you would see this is the most instantiated object!
A very common scenario one might come across while working with String class is how to split a string?
Answer:You can make use of the split method from the java.lang.String class.
Split method: public String[] split(String regex)
What does this method do? As you can see the split method takes in one argument of type String which is a regex (Regular Expression), so this method splits the string as per the provided regular expression.
Note that this method can throw a PatternSyntaxException if the regular expression syntax is not valid.
✌️ The spit(String regex) method was introduced in Java 1.4
Example 1. Split a String by comma (,)
Let's see an example, we have a String that is comma-separated containing names of Countries "USA, Japan, China, Austalia, Canada, Germany, France, Sweden, India, Sri Lanka, Russia, Poland" and we want to split this string by comma.
Code Snippet:package com.code2care.java.tutorials;
public class JavaStringSplitExample {
public static void main(String[] args) {
String countries = "USA, Japan, China, Austalia, Canada, Germany, "
+ "France, Sweden, India, Sri Lanka, Russia, Poland";
String[] countriesArr = countries.split(",");
for (String country : countriesArr) {
System.out.println(country.trim());
}
}
}
Output:
USA
Japan
China
Austalia
Canada
Germany
France
Sweden
India
Sri Lanka
Russia
Poland
Example 2. Split a String by Slash (/)
Code Snippet:String dataString = "11/22/2020";
String[] dateStringArr = dataString.split("/");
System.out.println("Date: " + dateStringArr[0]);
System.out.println("Month: " + dateStringArr[1]);
System.out.println("Year: " + dateStringArr[2]);
Output:
Date: 11
Month: 22
Year: 2020
Example 3. Split a String by Pipe (//|)
The first two examples we say worked by just passing the delimited as a string! Beware this will not work when the delimiter is a Pipe (you will get incorrect output) that's because the pipe has a special meaning in regEx, so you need to escape it using a backslash to use it as a character. Just add a double-slash \\ followed by |.
Code Snippet:String operatingSystems = "macOS|Windows|Linux|Unix";
String[] operatingSystemsArr = operatingSystems.split("\\|");
for (String os : operatingSystemsArr) {
System.out.println(os);
}
Output:
macOS
Windows
Linux
Unix
Example 4. Split a String by dot \\.)
Just like a pipe, the dot has a special meaning while using regEx so you need to escape it.
Code Snippet:public static void main(String[] args) {
String dataString = "111.2222.3333.4444";
String[] dataStringArr = dataString.split("\\.");
for (String data : dataStringArr) {
System.out.println(data);
}
}
Exception: java.util.regex.PatternSyntaxException:
If the provided regEx is invalid then you would see the below error stack,
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 0
${,}
^
at java.base/java.util.regex.Pattern.error(Pattern.java:2027)
at java.base/java.util.regex.Pattern.closure(Pattern.java:3320)
at java.base/java.util.regex.Pattern.sequence(Pattern.java:2213)
at java.base/java.util.regex.Pattern.expr(Pattern.java:2068)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1782)
at java.base/java.util.regex.Pattern.<init>(Pattern.java:1428)
at java.base/java.util.regex.Pattern.compile(Pattern.java:1068)
at java.base/java.lang.String.split(String.java:2317)
at java.base/java.lang.String.split(String.java:2364)
at com.code2care.java.tutorials.JavaStringSplitExample.main(JavaStringSplitExample.java:8)
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
- How to do a Print Screen on Windows 11 to Screencapture - Windows
- Where is Maven .m2 local repository located on Mac - HowTos
- Java: Convert String to InputStream - Java
- JSON Nest Objects Example: JSON Tutorial - Json-Tutorial
- How to clear Microsoft Teams Cache on Mac (macOS) - Teams
- Python: How to create a Dictionary of Lists with Examples - Python
- Android Shared Preferences API tutorial - Android
- How to Export a PowerShell Script/Cmdlet Output to a Text File - Powershell