Split Strings in Java

Split Strings in Java

Learn how to split strings in Java

Introduction

Splitting a Strings is common operation. This short tutorial will show some of the ways to complete is operation.

String.split()

The most common way to split a string is using the split() method from the String class. It splits the given String based on the delimiter and returns an array for Strings.

Let's try a few examples. First we'll start with splitting by a common:

// Split String By Comma
String[] colors = "red,yellow,green,blue".split(","); // ["red", "yellow", "green", "blue"]

Split By a Whitespace:

// Split String By Space
String[] names = "john bob harry".split(" "); // ["john", "bob", "harry"]

Split By a Period:

// Split String By Period
String[] number = "012.345.6789".split("\\."); // ["012", "345", "6789"]

String.split() with Limits

You can limit the size of the array return by passing a limit value to the split() method.

Let's try a few examples. First we'll return an array with two element:

// Split String By Space Using Limits (return array with two elements)
String[] lines = "The Sky Is Blue".split(" ", 2); // ["The", "Sky Is Blue"]

Split returns array with 3 elements:

// Split String By Space Using Limits (return array with three elements)
String[] lines = "The Sky Is Blue".split(" ", 2); // ["The", "Sky", "Is Blue"]

Conclusion

This tutorial cover different ways you can split a string in Java. You can find more tutorials on Java here

The source examples can be found here on GitHub.

Did you like it? Why don't you try also...

Change the Server Port that a Spring Boot App is running on

Change the Server Port that a Spring Boot App is running on

Learn how to change the server port that a spring boot application is running on.

Fill Java Array With The Same Values

Fill Java Array With The Same Values

Learn How To Fill a Java Array With All The Same Values.

Java How to Remove the First Character from a String.

Java How to Remove the First Character from a String.

Learn How to Remove the First Character From a String.