StringUtils substringBefore() Example in Java

In this post, we will see org.apache.commons.lang3.StringUtils substringBefore() example in Java.

import org.apache.commons.lang3.StringUtils;

public class StringUtilsExample {
    public static void main(String[] args) {
        String str = "Hello, world!";
        String substr = StringUtils.substringBefore(str, ",");
        System.out.println(substr); // Output: Hello
    }
}

Output – Hello

In this example, we import the StringUtils class from the Apache Commons Lang library, and then define a string str that contains the text “Hello, world!”. We then use the substringBefore() method to extract the substring before the comma, which is “Hello”, and store it in the substr variable. Finally, we print the substr variable to the console, which outputs “Hello”.

We need to add the below dependency in maven to use org.apache.commons.lang3.StringUtils substringBefore() method. We can download the apache-commons maven dependency from here.

Note – The StringUtils class provides a different method contains() to check string contains whitespace or not.

pom.xml changes

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>

That’s all about StringUtils substringAfter() example in Java.

See docs.

Related post.