Before you go, check out these stories!

0
Hackernoon logoHow To Split Strings in Java by@harrisonbrock

How To Split Strings in Java

Author profile picture

@harrisonbrockHarrison Brock

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.

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!