string.split()

String.split(String delimiter, int limit) break string by using delimiter and return array.
delimiter : any string or regular expression
limit : (Optional ) number of elements our output array will have.

Here are some examples with output.
String str = "22/05/2020";
String[] my_array=str.split("/");

// displaying elements of the array //
for (int i=0; i < my_array.length; i++)
{
  System.out.println(my_array[i]);
}
Output is here
22
05
2020
After getting an array we used for loop to display all elements of the array ( my_array ). We can find out number of elements present inside array by using length.
In above code change this line by adding limit. Now our output array will have 2 elements. The delimiter is used to break the string once only. After breaking rest of the string is returned as second element.
String[] my_array=str.split("/",2);
Now our output will be
22
05/2020

Separating userid and domain part from an email address

String str = "my_userid@example.com";
String[] my_array=str.split("@");

System.out.println("userid part : " +my_array[0]);
System.out.println("domain part : " +my_array[1]);
Output
userid part : my_userid
domain part : example.com

Using regular expression

We can use space as delimiter to break the string. Here \\s indicates one space.
String str = "Welcome to plus2net";
String[] my_array=str.split("\\s");
// displaying elements of the array //
for (int i=0; i < my_array.length; i++)
{
  System.out.println(my_array[i]);
}
Output
Welcome
to
plus2net
In above code change the like like this . ( Break the string by any number)
String[] my_array=str.split("[0-9]");
Output
Welcome to plus
net
The above code takes any digit as delimiter and break the string.

We can use all chars between m and p ( both inclusive ) to break the string.
String[] my_array=str.split("[m-p]");
Output
Welc

e t
 
lus2
et
Like this we can apply several regular expression patterns to break string.

All String functions

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer