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
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
splitted // "name"
More Java Articles
- How to Remove the Last Character in a String in Java
- How to Remove the First Character in a String in Java
- How to Split a String Over Only the First Occurrence in Java
- How to Pass Dynamic Number of Parameters in Java
- How to Use Generics with Abstract Classes in Java For Different Parameter Types
- How to Replace the String Between Two Characters in Java
- How to Print Elements of a List in Java Without Loops
- How to Ignore Test Cases in JUnit
- How to Add Multiple Elements to List At Once in Java