How to get the Substring before a Character in Java

Updated onbyAlan Morel
How to get the Substring before a Character in Java

When you work with strings that you know is in a specific format, you can use this to your advantage to extract pieces of data from it.

More specifically, if you know the string will contain a specific character, you can get the substring before that character and use it for whatever you need.

In this post, we'll learn all the different ways we can get the substring before a character in Java.

Using split

An easy way to accomplish this is to just split the string on the character you want to extract.

This will divide up the string into an array of string values, with the first element being what you want.

Let's start with our example string:

JAVA
String string = "Hello:World";

Let's say we wanted to get the substring before the colon:

JAVA
String string = "Hello:World"; String[] split = string.split(":"); String value = split[0]; System.out.println(value);
BASH
Hello

Using indexOf and substring

Another, more manual way to do this is to use the indexOf() method to get the index of the character you want to extract.

With this index, you can then use the substring() method to get the substring before that index.

JAVA
String string = "Hello:World"; int index = string.indexOf(":"); String value = string.substring(0, index); System.out.println(value);
BASH
Hello

The benefit of this approach is that have the value of the index already there, in case you need it for something else down the line.

Conclusion

In this post, we looked at the best easiest ways to extract a substring before a character in a string.

You can either split the string or search for the character and then use the substring() method to get the substring you want.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.