Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

split()

Example

Divide a string into an array containing its constituent substrings.

String myStr = "Split a string by spaces, and also punctuation.";
String regex = "[,\\.\\s]";
String[] myArray = myStr.split(regex);
for (String s : myArray) {
  System.out.println(s);
}

Definition and Usage

The split() method in Java divides a string into an array of substrings using a regular expression as the separator.

When a limit is defined, the resulting array won’t exceed this limit. The final element of the array holds the remaining portion of the string, which might include separators if the limit was reached.

Suggestion: Refer to the Java RegEx tutorial for a deeper understanding of regular expressions.

Syntax

One of the following:

public String[] split(String regex, int limit)
public String[] split(String regex)

Parameter Values

Parameter

Description

regex

Necessary: a regular expression that specifies the separators at which the string will be divided.

limit

Optional: the maximum size of the resulting array.

Technical Details

Returns:

A string array.

Throws:

PatternSyntaxException occurs when the syntax of the regular expression is incorrect.

Java Version:

1.4