Saturday, January 11, 2025
HomeComputer ScienceJava String split() Method with Examples

Java String split() Method with Examples

he String.split() method in Java is used to split a string into an array of substrings based on a specified delimiter (or regular expression). It is part of the java.lang.String class.

Syntax:

java
public String[] split(String regex)
public String[] split(String regex, int limit)
  • regex: A regular expression that defines the delimiter.
  • limit (optional): The number of substrings to return. If the limit is:
    • Greater than 0: Splits the string into at most limit parts.
    • Equal to 0: Splits the string and removes trailing empty strings.
    • Less than 0: Splits the string with no limit on the number of parts.

Examples of split() Method

1. Basic Splitting Using a Space

java
public class SplitExample {
public static void main(String[] args) {
String str = "Java is fun";
String[] words = str.split(" ");

for (String word : words) {
System.out.println(word);
}
}
}

Output:

kotlin
Java
is
fun

2. Splitting Using a Comma

java
public class SplitExample {
public static void main(String[] args) {
String str = "apple,orange,banana";
String[] fruits = str.split(",");

for (String fruit : fruits) {
System.out.println(fruit);
}
}
}

Output:

apple
orange
banana

3. Using a Regular Expression

java
public class SplitExample {
public static void main(String[] args) {
String str = "Java123Python456C++";
String[] languages = str.split("\\d+"); // Split using digits as the delimiter

for (String language : languages) {
System.out.println(language);
}
}
}

Output:

mathematica
Java
Python
C++

4. Limiting the Number of Splits

java
public class SplitExample {
public static void main(String[] args) {
String str = "one:two:three:four";
String[] parts = str.split(":", 2); // Split into 2 parts

for (String part : parts) {
System.out.println(part);
}
}
}

Output:

makefile
one
two:three:four

5. Removing Trailing Empty Strings

java
public class SplitExample {
public static void main(String[] args) {
String str = "a,b,c,,,";
String[] parts = str.split(",", 0); // Removes trailing empty strings

for (String part : parts) {
System.out.println(part.isEmpty() ? "Empty" : part);
}
}
}

Output:

css
a
b
c

Key Points to Remember

  1. The split() method uses regular expressions for the delimiter, so characters like . or | must be escaped (\\., \\|).
  2. An empty string as a delimiter will result in splitting the string into individual characters.
  3. Using limit can control how the string is divided, making it flexible for various use cases.

The split() method is a powerful tool for parsing and processing strings in Java.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Antonym of Genre?

HTML Background Images

LMFAO Full Form

Recent Comments

0
Would love your thoughts, please comment.x
()
x