×

Java String split() method

Java String split() method split current String against given regular expression and returns a char array.

Syntax:

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

Parameters:

regex : it is a regular expression to be applied on String.

limit : it is limit for the number of Strings in array. If it is zero , it will return all String matching regex.

Returns:

array of Strings

Throws:

PatternSyntaxException if pattern for regex is invalid.

Java String split() method 1 example:

public class JavaStringSplitEx1
    { 
       public static void main(String args[])
       { 
         String s1="Welcome to the Tutorial and example"; 
         String[] words=s1.split("\\s");//splits the string based on whitespace 
    //using java foreach loop to print elements of string array 
        for(String w:words){ 
          System.out.println(w); 
         } 
       }
    }

Output:

Welcome
to
the
Tutorial
and
example

Java String split() method with regex and length example 2

    public class JavaStringSplitEx2
    { 
    public static void main(String args[])
    { 
    String s1="welcome to tutorialsandexample world"; 
    System.out.println("returning words:"); 
    for(String w:s1.split("\\s",0)){ 
    System.out.println(w); 
    } 
        System.out.println(""); 
    System.out.println("returning words:"); 
    for(String w:s1.split("\\s",1)){ 
    System.out.println(w); 
    } 
       System.out.println(""); 
    System.out.println("returning words:"); 
    for(String w:s1.split("\\s",2)){ 
    System.out.println(w); 
    } 
    }      
    }

Output:

returning words:
welcome
to
tutorialsandexample
world
returning words:
welcome to tutorialsandexample world
returning words:
welcome
to tutorialsandexample world

Java String split() method with regex and length example 3

    public class JavaStringSplitEx3 { 
        public static void main(String[] args) { 
            String str = "Tutorialand Example"; 
            System.out.println("Returning words:"); 
            String[] arr = str.split("t", 0); 
            for (String w : arr) { 
                System.out.println(w); 
            } 
            System.out.println("Split array length: "+arr.length); 
        } 
    }

Output:

Returning words:
Tu
orialand Example
Split array length: 2

Java String split() method with regex and limit example 4

 public class JavaStringSplitEx4
{
    public static void main(String args[])
    {
        String str = "Tutorial&&And&&Example";
        String [] arrOfStr = str.split("&", 5);
        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output:

Tutorial
And
Example

Java String split() method example 5

public class JavaStringSplitEx5
{
    public static void main(String args[])
    {
        String str = "Tutorial&&And&&Example";
        String [] arrOfStr = str.split("&",-2);
        for (String a : arrOfStr)
            System.out.println(a);
    }
}

Output:

Tutorial
And
Example

Related Topics

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Java throw

Java throw Sometimes it is required in the code to throw an exception deliberately. In order to achieve the same, the Java throw keyword should be used. One can throw either...

3 minutes read.

Java Integer toOctalString() method

The toOctalString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 8. Syntax public static String toOctalString (int  i) Parameters The parameter ‘i’ represents...

1 minute read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

Graph Problems in Java

A graph is a special type of data structure used in programming that is made up of edges connecting each set of finitely many nodes, or vertices, to each other....

14 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.