stringsubstringapache-stringutilsstring-utils

Extract string using StringUtils


Let's take a string "aabaabaa" and I want to know the position of "aa" in middle or from last.

For example position of "aa" from right should be : 6 (taking start insex as 0)


Solution

  • This can easily be done using StringUtils present in Apache commons. Here is the complete example on the usage.

    public static int indexOfIgnoreCase(String str,
                                        String searchStr,
                                        int startPos)
    

    Case in-sensitive find of the first index within a String from the specified position.

    A null String will return -1. A negative start position is treated as zero. An empty ("") search String always matches. A start position greater than the string length only matches an empty search String.

    StringUtils.indexOfIgnoreCase(null, *, *)          = -1
    StringUtils.indexOfIgnoreCase(*, null, *)          = -1
    StringUtils.indexOfIgnoreCase("", "", 0)           = 0
    StringUtils.indexOfIgnoreCase("aabaabaa", "A", 0)  = 0
    StringUtils.indexOfIgnoreCase("aabaabaa", "B", 0)  = 2
    StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
    StringUtils.indexOfIgnoreCase("aabaabaa", "B", 3)  = 5
    StringUtils.indexOfIgnoreCase("aabaabaa", "B", 9)  = -1
    StringUtils.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
    StringUtils.indexOfIgnoreCase("aabaabaa", "", 2)   = 2
    StringUtils.indexOfIgnoreCase("abc", "", 9)        = 3
    

    Parameters:

    Returns: The first index of the search String, -1 if no match or null string input