a shot of dev knowledge

RELATED TAGS

What is StringUtils.containsOnly in Java?

containsOnly() is a staticA member in a Java program can be declared as static using the keyword “static” preceding its declaration/definition. method of the StringUtils class that is used to check whether a given string contains only valid characters.

The characters in the string can be repeated any number of times, but they have to be a subset of the defined valid characters.

For example:


valid characters = "abc"   
string = "ababaaaabbbcccac"

Since the string contains only valid characters, containsOnly would return true.


valid characters = "abc"   
string = "ababadefaabbbcccac"

Since the string contains characters that are not valid, containsOnly would return false.

Adding the apache commons lang package

StringUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml file.


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

For other versions of the commons-lang package, refer to the Maven Repository.

Importing StringUtils

You can import the StringUtils class as follows.

import org.apache.commons.lang3.StringUtils;

Syntax


public static boolean containsOnly(final CharSequence cs, final char... valid)

Parameters

  • final CharSequence cs: the character sequence to check for valid characters.

  • final char... valid: an array of valid characters.

Return value

The function returns true if the character sequence only contains passed valid characters and is not null. Otherwise, it returns false.

Overloaded method


public static boolean containsOnly(final CharSequence cs, final String validChars)

Parameters

  • final String validChars: a string of valid characters.

Return value

The function returns true if the character sequence only contains passed valid characters and is not null. Otherwise, it returns false.

Code

In the code below, we define an array of valid characters and a sequence of characters.

import org.apache.commons.lang3.StringUtils;

public class Main{

    public static void main(String[] args){
        String characterSequence = "abbbcccaaaccb";
        char[] validChars = "abc".toCharArray();
        System.out.println(StringUtils.containsOnly(characterSequence, validChars));

        characterSequence = "abcdef";
        System.out.println(StringUtils.containsOnly(characterSequence, validChars));
    }
}

Output

The output of the code will be as follows.


true
false

Explanation

This is because the first sequence of characters contains only valid characters, and the second sequence of characters contains extra characters that are not defined in the array of valid characters.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring