What is the StringUtils.indexOfAnyBut method in Java?
Overview
In Java, indexOfAnyBut() is a StringUtils class, which is used to find the first index of any character from a character sequence that is not present in the set of search characters. If no such index can be found, the method returns -1.
Import StringUtils
The definition of StringUtils can be found in the Apache Commons Lang package, which we can add 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>
Note: For other versions of the commons-lang package, refer to the Maven Repository.
We can import the StringUtils class as follows:
import org.apache.commons.lang3.StringUtils;
Syntax
public static int indexOfAnyBut(final CharSequence cs, final char... searchChars)
Parameters
cs: The character of a sequence or a string to search in.searchChars: The list of search characters.
Return value
This method returns an integer.
Example
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>test</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>Main</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>Note: The maven dependency for
StringUtilsis included in thepom.xmlfile.
Explanation
-
Lines 1–2: We import the
StringUtilsandclasses. -
Line 7: We define the character sequence called
text. -
Line 8: We define the list of characters to be searched named
searchChars. -
Line 9: We call the
indexOfAnyButmethod withtextandsearchCharsas parameters. The method returns the index,2, of the first characterl. -
Line 10: We assign a new list of characters to
searchChars. -
Line 12: We call the
indexOfAnyButmethod withtextandsearchCharsas parameters. The method returns-1indicating that there are no characters that occur in thetextbut not insearchChars.