【Java源码分析】String 字符串索引查找 indexOf
indexOf()
indexOf() 方法有以下四种形式:
返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
-
public int indexOf(int ch): public int indexOf(int ch, int fromIndex): 。 int indexOf(String str): int indexOf(String str, int fromIndex)
参数
-
ch – 字符,Unicode 编码。如a-97 fromIndex – 开始搜索的索引位置,第一个字符是 0 ,第二个是 1 ,以此类推。 str – 要搜索的子字符串。
返回值
查找字符串,或字符 Unicode 编码在字符串出现的位置:
实例
public class Main { public static void main(String args[]) { String string = "aaa456ac"; System.out.println(string.indexOf("b")); // -1,"b"不存在 // 从第四个字符位置开始往后继续查找,包含当前位置 System.out.println(string.indexOf("a",3));// 6 //a-97,b-98,c-99 System.out.println(string.indexOf(99));//indexOf(int ch);返回结果:7 System.out.println(string.indexOf(c));//indexOf(int ch);返回结果:7 //从fromIndex查找ch System.out.println(string.indexOf(97,3));// 返回结果:6 System.out.println(string.indexOf(a,3));//返回结果:6 } }
输出结果为:
指定子字符串在字符串中第一次出现处的索引,从指定的索引开始。
源码
public int indexOf(String str) { return indexOf(str, 0);//默认偏移0 } public int indexOf(String str, int fromIndex) { return indexOf(value, 0, value.length, str.value, 0, str.value.length, fromIndex); } static int indexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex) { if (fromIndex >= sourceCount) {//偏移比源字符串长 return (targetCount == 0 ? sourceCount : -1);//目标长度不为0,返回-1 } if (fromIndex < 0) {//偏移小于0改为0 fromIndex = 0; } if (targetCount == 0) {//目标数据长度为0,返回偏移 return fromIndex; } char first = target[targetOffset];//目标数组偏移后首字符 int max = sourceOffset + (sourceCount - targetCount);//遍历最大值 for (int i = sourceOffset + fromIndex; i <= max; i++) {//从偏移量开始 /* 查找第一个字符. */ if (source[i] != first) { while (++i <= max && source[i] != first); } /* 查找第一个字符后查找剩余的 */ if (i <= max) { int j = i + 1; int end = j + targetCount - 1; for (int k = targetOffset + 1; j < end && source[j] == target[k]; j++, k++); if (j == end) { /* 查找到整个字符串返回. */ return i - sourceOffset; } } } return -1; } public int indexOf(int ch, int fromIndex) { final int max = value.length; if (fromIndex < 0) { fromIndex = 0; } else if (fromIndex >= max) { // Note: fromIndex might be near -1>>>1. return -1; } if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { // handle most cases here (ch is a BMP code point or a // negative value (invalid code point)) final char[] value = this.value; for (int i = fromIndex; i < max; i++) { if (value[i] == ch) {//注意:a==97 return i; } } return -1; } else { return indexOfSupplementary(ch, fromIndex); } }
先查找第一个字符,查找到第一个字符后查找剩余的,如果查找到整个字符串返回。
上一篇:
IDEA上Java项目控制台中文乱码