Ticker

6/recent/ticker-posts

Split() String Method in Java

Split() String Method in Java

Introduction

The split() method in Java is used to split a string into an array of substrings based on a specified delimiter. It allows you to break down a larger string into smaller components for easier manipulation and analysis. The method returns an array of strings that were separated by the specified delimiter.

Syntax

java
public String[] split(String regex)

Parameters

  • regex: The regular expression that defines the delimiter used for splitting the string.

Return Value

  • An array of strings containing the substrings obtained after splitting the original string.

Example
Suppose we have a string that contains names separated by commas, and we want to split it into individual names.

java
public class StringSplitExample {
public static void main(String[] args) {
String names = "John,Doe,Jane,Smith,Alice";

// Split the names using the comma as the delimiter
String[] nameArray = names.split(",");

// Print each name from the array
for (String name : nameArray) {
System.out.println(name);
}
}
}

Explanation
In the code example above, we first define a string called names, which contains a list of names separated by commas. We then use the split() method with the comma (,) as the delimiter to split the string into an array of substrings. The resulting array, nameArray, holds individual names as its elements.

The for-each loop is used to iterate through the nameArray and print each name on a new line.

Output


John
Doe
Jane
Smith
Alice

In this output, we can see that the split() method successfully divided the original string into separate names based on the comma delimiter.

Additional Notes

  1. If the specified regex is not found in the original string, the split() method will return an array containing the original string as its only element.
  2. The split() method also has an overloaded version that takes an additional limit parameter, which limits the number of substrings produced after splitting.

Remember to handle potential exceptions when working with the split() method. For instance, if the regex pattern is invalid, a PatternSyntaxException may be thrown.

Post a Comment

0 Comments