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)
- Create a Zip file using Java Code programmatically
- Eclipse : A java Runtime Environment (JRE) or Java Development kit (JDK) must be available
- How to Sort a LinkedList in Java
- Loading class com.mysql.jdbc.Driver. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver
- How to declare and initialize Array in Java Programming
- [Fix] java: integer number too large compilation error
- Java JDBC Connection with MySQL Driver in VS Code + Troubleshooting
- Reading .xls and .xlsx Excel file using Apache POI Java Library
- IntelliJ: Error: Could not find or load main class, java.lang.ClassNotFoundException
- How to get Client IP address using Java Code Example
- Truncate table using Java JDBC Example
- Struts 2 : There is no Action mapped for namespace [/] and action name [form] associated with context path [/proj]
- How to get file path in Idea IntelliJ IDE
- Java Generics explained with simple definition and examples
- Java SE 8 Update 301 available with various bug fixes and security improvements
- Java: Collect Stream as ArrayList or LinkedList
- Java JDBC Connection with PostgreSQL Driver Example
- How to check if Java main thread is alive
- How to fix Java nio NoSuchFileException wile reading a file
- Java 8+ get Day of the Week Examples with LocalDateTime, DateTime, ZonalDateTime and Instant classes
- Ways to Convert Integer or int to Long in Java
- [Java] How to throws Exception using Functional Interface and Lambda code
- [Fix] Spring Boot: mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
- Java: The value of the local variable string is not used
- Java JDBC: Insert Java 8 LocalDate and Time using PreparedStatement
- How to open TextEdit from Mac Terminal - MacOS
- How to Install Microsoft Teams App on M1 or M2 Mac - Teams
- Open New Terminal Window Using Keyboard Shortcut macOS - MacOS
- Steps to Delete or Deactivate Instagram Account - HowTos
- Error 50057 - User account is disabled. The account has been disabled by an administrator [Microsoft - Teams - Azure] - Microsoft
- Ezoic: My Honest Review after 100 Days of Use - Maximizing Revenue with a Personal Touch - 2022
- java: ']' expected error [fixed] - Java
- MySQL 1005 Error : SQLSTATE: HY000 (ER_CANT_CREATE_TABLE) Message: Can't create table '%s' (errno: 150) - MySQL