Java string split Method | Regex With Space, Comma, Dot Examples

A Java string Split methods have used to get the substring or split or char form String. The split method works on the Regex matched case, if matched then split the string sentences.

You can split a string with many time regular expressions, here are some Splitting Regex can be:

  • Space (Whitespace) – (“\\s”)
  • Comma (“,”)
  • Dot (“\\.”)
Java string split Method Regex With Space, Comma, Dot Examples

Syntax

There is two Syntax of the split() method in a Java string.

Parameter

  • regex: regular expression required to splitting point.
  • limit: Number of strings in Array, if the value is 0 (zero) then it will do splitting on complete strings

Return Value: 

The split () method will return a String Arrays.

Java string split example (space)

In the example First, create and assign the string variable “str1“. Then create a string array and split the str1 with space.

The method returns the Array string and stores the value in strArray. Then do iteration with Java for-each loop and print the values. Array indexing starts with zero.

The example and program of Java string split with space.

Output: How
to
split
Strings
in
Java

string split with Comma ( , ) in Java

An upper example has split the string with space now see the example of how to do it with Comma. We are using Java for loop in this example. For its very easy regex just pass like that, Regex - (",")

Output: Split
method
with
comma

string split with a Dot  ( . ) in Java

Let’s Do the same thing with dot example in Java. For that, you have to pass the regex - ("\\.")

Output: Split
method
with
dot

How Java String split() method with regex and length example.

Let’s do Use and see how it’s work with when splitting a String in Java.

Output Screenshot:

How Java String split() method with regex and length example output

 

QA: How to get a Single value from strings after splitting?

It’s a very easy just pass the index value in string array after a splitting. Here is the example code of getting the first value form string.

Output: Split

Sidenotes:  As the Same example of a Split method with regex and length, you can do with number or string to split a strings sentences in java.

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Java string split Examples are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.