How to Get the Substring Before a Character in Java
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 :.
1. Using split()
We can use the split() method to do this.
String[] splitted = str.split(":");
// ["name", "description"]
This will yield an array of strings containing the substrings around the given delimiter, which is a colon in this case.
Note that
split()takes the delimiter’s regular expression, so we can match more than just a single character.
We can then obtain the first element of the array, which will be name.
String substr = splitted[0] // "name"
2. Using indexOf() and substring()
We can obtain the first occurrence of a character using indexOf().
int delimiterIndex = str.indexOf(":");
If no delimiter exists, indexOf() will return -1. We can check for this and conditionally run substring() to get the substring up to that index.
if (delimiterIndex != -1) {
String substr = str.substring(0 , delimiterINdex) // "name"
}
3. Using StringUtils.substringBefore()
If we’re using commons-lang, we can make use of StringUtils.substringBefore() to achieve the same functionality.
String substr = StringUtils.substringBefore(str, ":"); // "name"