1. indexOf()方法
indexOf()方法来自java.lang.String.indexOf();
返回值类型为int;
1.1 源代码
//源代码
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);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
char first = target[targetOffset];
int max = sourceOffset + (sourceCount - targetCount);
for (int i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source[i] != first) {
while (++i <= max && source[i] != first);
}
/* Found first character, now look at the rest of v2 */
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) {
/* Found whole string. */
return i - sourceOffset;
}
}
}
return -1;
}
1.2 使用方法
public static void main(String[] args){
String example = "巴啦啦小魔仙";
String son = "巴啦啦";
//返回值类型为int
//调用indexOf()
int result = example.indexOf(son);
//返回-1代表不包含
if (result == -1){
System.out.println(example+"中不包含"+son);
//返回非-1代表包含
}else {
System.out.println(example+"中包含"+son);
}
}