How to Get the Substring Before a Character in Java

Published Aug 31, 2021

How can we obtain the substring before a character in Java?

Suppose we have this string.

String str = "name:description";

We want to obtain name, before the colon :.

We can use the split() method to do this.

String[] splitted = str.split(":");
// ["name", "description"]

This will give us an array of strings containing the substrings around the given delimiter, which is a colon in this case.

We can then obtain the first element of the array, which will be name.

splitted[0] // "name"

More Java Articles