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...

Java Strings: Testing if a String is Empty or Blank

Java Strings: Testing if a String is Empty or Blank

Learn to test if a String is Empty or Blank

Java Strings: Basic String Methods Part 1

Java Strings: Basic String Methods Part 1

Learn the most common Java String Methods.

Java String: Title Case Format

Java String: Title Case Format

Learn How to Convert Java String to Title Case Format