- Java String split() Method
- String split() Method Syntax
- Important Points About String split() Method
- Java String split() Examples
- String split() Examples using JShell
- Reference
- How to split String into Array [Practical Examples]
- Getting started with Split String into Array Examples
- Syntax
- Examples to split String into Array
- Example 1 : Split String into Array with given delimiter
- Example 2 : Split String into Array with delimiter and limit
- Example 3 : Split String into Array with another string as a delimiter
- Example 4 : Split String into Array with multiple delimiters
- Example 5 : Split the String without using built-in split function
- Example 6 : Split the content read from the file line wise
- Example 7 : Count the number of words in a string using split method
- Summary
- References
- Leave a Comment Cancel reply
- Java Tutorial
Java String split() Method
Java String split() method returns a String array. It accepts string argument and treats it as regular expression. Then the string is split around the matches found.
String split() Method Syntax
There are two overloaded split() methods.
- public String[] split(String regex, int limit) : The limit argument defines the result string array size. If the limit is 0 or negative then all possible splits are part of the result string array.
- public String[] split(String regex) : This is a shortcut method to split the string into maximum possible elements. This method calls split(regex, 0) method.
Important Points About String split() Method
- The result string array contains the strings in the order of their appearance in this string.
- If there are no matches, then the result string array contains a single string. The string element has the same value as this string.
- We can use split() method to convert CSV data into a string array.
- Trailing empty strings are not included in the result. For example, «A1B2C3D4E5».split(«3») will result in the string array [A, B, C, D, E] .
Java String split() Examples
Let’s look at some simple examples of split() method.
package net.javastring.strings; import java.util.Arrays; public class JavaStringSplit < public static void main(String[] args) < String s = "Hello World 2019"; String[] words = s.split(" "); System.out.println(Arrays.toString(words)); String s1 = "A1B2C3D4E5"; String[] characters = s1.split("8"); System.out.println(Arrays.toString(characters)); String[] twoWordsArray = s.split(" ", 2); System.out.println(Arrays.toString(twoWordsArray)); System.out.println(Arrays.toString(s.split("X", 2))); String s2 = "A1B2C3D "; System.out.println(Arrays.toString(s2.split("4"))); >>
[Hello, World, 2019] [A, B, C, D, E] [Hello, World 2019] [Hello World 2019] [A, B, C, D ]
String split() Examples using JShell
We can run some examples using jshell too.
jshell> "Hello World 2019".split(" "); $34 ==> String[3] < "Hello", "World", "2019" >jshell> "A1B2C3D4E5".split("2"); $35 ==> String[5] < "A", "B", "C", "D", "E" >jshell> "Hello World 2019".split(" ", 2); $36 ==> String[2] < "Hello", "World 2019" >jshell> " A1B2C3D ".split("2"); $37 ==> String[4] < " A", "B", "C", "D " >jshell>
Reference
How to split String into Array [Practical Examples]
Getting started with Split String into Array Examples
In many real time applications, we may need to work on the words of the string rather than the whole strings. In this case, we will need to split the string into its equivalent words. Java provides the split() function in a string class that helps in splitting the string into an array of string values. There are variety of ways in which we can use the split function depending on our requirement.
Syntax
The split function is used in two different variants as shown below.
split(String regex) String[] split(String regex, int limit)
The first one is used to splits this string around matches of the given regular expression. Whereas, in the second variant an additional parameter limit specifies the number of times the regex will be used as a splitting character. Here, regex parameter is a delimiter used to split the words.
Examples to split String into Array
Example 1 : Split String into Array with given delimiter
In this example, we are simply splitting the string using the space as a delimiter. However, we are not limiting to the number of times delimiter is used. Therefore, it will split whole string into an Array of strings.
// Program to split String into array using space delimiter public class Main < public static void main(String[] args) < // Declaring and Initializing the variables String s = "Welcome to the world of java programming "; // Using split function String[] a = s.split(" "); // Printing the resultant array for (String i: a) System.out.println(i); >>
Welcome to the world of java programming
Example 2 : Split String into Array with delimiter and limit
In this example, we are simply splitting the string using the space as a delimiter. Moreover, we are adding the limit as 3. Therefore, it will split the string using the space delimiter for 2 times.
// Program to split String into array using space delimiter and limit public class Main < public static void main(String[] args) < // Declaring and Initializing the variables String s="Welcome to the world of java programming "; // Using the split function String[] a = s.split(" ",3); // Printing the resultant array for (String i : a) System.out.println(i); >>
Welcome to the world of java programming
Example 3 : Split String into Array with another string as a delimiter
In this example, we are splitting the string using the another string as a delimiter. However, we are not adding any limit.
// Program to split String into array using other string as a delimiter public class Main < public static void main(String[] args) < // Declaring and Initializing the variables String s = "Life is a book. Life is a Journey. Life is a Rose Garden."; String d = "Life is a "; // Using the split function String[] a = s.split(d); // Printing the resultant array for (String i: a) System.out.println(i); >>
Example 4 : Split String into Array with multiple delimiters
In this example, we are splitting the string using the multiple character as a delimiter. Therefore, if any of the delimiting character is found, it will split the string and store it in an array.
// Program to split String into array using multiple delimiters public class Main < public static void main(String[] args) < // Declaring and Initializing the variables String s = "Life is a book. Life is a Journey! Is life is a Rose Garden?"; // Using split function String[] a = s.split("[. ]"); // Printing the resultant array for (String i: a) System.out.println(i); >>
Life is a book Life is a Journey Is life is a Rose Garden
Example 5 : Split the String without using built-in split function
In this example, we are splitting the string using the multiple character as a delimiter. Therefore, if any of the delimiting character is found, it will split the string and store it in an array.
// Program to split String into array without using built-in split function public class Main < public static void main(String[] args) < // Declaring and Initializing the variables String s = "Welcome to the world of java programming "; String[] a = new String[8]; int j = 0; a[0] = ""; // Iterating over string character by character for (int i = 0; i < s.length(); i++) < // If char is a space we increment the array index by 1 and store the next value as a next word if (s.charAt(i) == ' ') < j++; a[j] = ""; >else < a[j] = a[j] + s.charAt(i); >> // Printing the resultant array for (String i: a) System.out.println(i); > >
Welcome to the world of java programming
Example 6 : Split the content read from the file line wise
In this example, we are splitting the content of file line wise. So, the delimiter is a new line character( \n ). Therefore, if any of the delimiting character is found, it will split the string and store it in an array.
The content of the text file is as shown below.
Test.txt Welcome to the world of Java Programming Its fun to learn Programming Have a good day!!
import java.io.*; public class Main < public static void main(String[] args) throws Exception < // Creating a file handle and bufferedreader object File file = new File("Test.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String st, fs = ""; // Reading from the file while ((st = br.readLine()) != null) fs = fs + st + "\n"; // Spliting into an array and printing String[] a = fs.split("\n"); for (String i: a) System.out.println(i); >>
Example 7 : Count the number of words in a string using split method
In this example, we are splitting the string using the multiple character as a delimiter. Therefore, if any of the delimiting character is found, it will split the string and store it in an array.
// Program to split String into array using multiple delimiters public class Main < public static void main(String[] args) < // Declaring and Initializing the variables String s = "Life is a book. Life is a Journey! Is life is a Rose Garden?"; // Using split function String[] a = s.split(" "); // Printing the resultant array for (String i: a) System.out.println(i); System.out.println("Total number of words in a string is " + a.length); >>
Life is a book. Life is a Journey! Is life is a Rose Garden? Total number of words in a string is 14
Summary
The knowledge of Splitting a string to an array in Java is very useful while working on real time applications. In this tutorial, we covered the way to split string into array using the built-in split function and without using split function. As per the requirement of an application, we can choose an appropriate approach for splitting. We learned in detail about splitting with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on splitting a string to an array in Java.
References
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Leave a Comment Cancel reply
Java Tutorial
- Set Up Java Environment
- Set Up Java on Linux
- Set up Java with BlueJ IDE
- Set up Java with VSC IDE
- Set up Java with Eclipse IDE
- Java Multiline Comments
- Java Variables
- Java Global Variables
- Java Date & Time Format
- Different Java Data Types
- Java Booleans
- Java Strings
- Java Array
- Java Byte
- Java convert list to map
- Java convert double to string
- Java convert String to Date
- Java convert Set to List
- Java convert char to int
- Java convert long to string
- Java Operators Introduction
- Java Boolean Operators
- Java Relational Operators
- Java Arithmetic Operators
- Java Bitwise Operators
- Java Unary Operators
- Java Logical Operators
- Java XOR (^) Operator
- Java Switch Statement
- Java If Else Statement
- Java While Loop
- Java For / For Each Loop
- Java Break Continue
- Java Nested Loops
- Java throw exception
- Java Try Catch
- Java Accessor and Mutator Methods
- Java main() Method
- IndexOf() Java Method
- Java ListIterator() Method
- Java create & write to file
- Java read file
- Java Parameter
- Java Argument
- Java Optional Parameters
- Java Arguments vs Parameters
- Java Arrays.asList
- Java HashSet
- Java Math
- Java HashMap vs Hashtable vs HashSet
- Java LinkedList
- Linked List Cycle
- Java List vs LinkedList
- Java ArrayList vs LinkedList