本帖最后由 李天甲 于 2012-6-21 08:40 编辑
空字符串和空格不太一样吧...
如果是空格的话,那么当然位置就是6.但是空字符串的话一般是第一个或者最后一个.
str.indexOf("") 和str.lastIndexOf("")分别返回的是0,和最大值.- /**
- * Code shared by String and StringBuffer to do searches. The
- * source is the character array being searched, and the target
- * is the string being searched for.
- *
- * @param source the characters being searched.
- * @param sourceOffset offset of the source string.
- * @param sourceCount count of the source string.
- * @param target the characters being searched for.
- * @param targetOffset offset of the target string.
- * @param targetCount count of the target string.
- * @param fromIndex the index to begin searching from.
- */
- static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
- char[] target, int targetOffset, int targetCount,
- int fromIndex) {
- /*
- * Check arguments; return immediately where possible. For
- * consistency, don't check for null str.
- */
- int rightIndex = sourceCount - targetCount;
- if (fromIndex < 0) {
- return -1;
- }
- if (fromIndex > rightIndex) {
- fromIndex = rightIndex;
- }
- /* Empty string always matches. */
- if (targetCount == 0) {
- return fromIndex;
- }
- int strLastIndex = targetOffset + targetCount - 1;
- char strLastChar = target[strLastIndex];
- int min = sourceOffset + targetCount - 1;
- int i = min + fromIndex;
- startSearchForLastChar:
- while (true) {
- while (i >= min && source[i] != strLastChar) {
- i--;
- }
- if (i < min) {
- return -1;
- }
- int j = i - 1;
- int start = j - (targetCount - 1);
- int k = strLastIndex - 1;
- while (j > start) {
- if (source[j--] != target[k--]) {
- i--;
- continue startSearchForLastChar;
- }
- }
- return start - sourceOffset + 1;
- }
- }
复制代码 上面是jdk查找lastIndexOf的代码,如果你调试一下就可以看到,当被查找字段为("");时,传递进去的被查找的对象也就是 @param target the characters being searched for.是一个字符数组char[].而这个值是空也就是说char[] target等于空数组...
在非空里面查找空数组,自然返回的是第一个或者最后一个..呵呵
|