문제

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)

도움이 되었습니까?

해결책

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:

  • str - the String to check, may be null
  • searchStr - the String to find, may be null
  • startPos - the start position, negative treated as zero

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top