Java教程-Java String indexOf()方法

Java String类的indexOf()方法返回指定字符串中指定字符或字符串的第一次出现位置。
语法
Java中有四种重载的indexOf()方法。indexOf()方法的签名如下:
No. | Method | Description |
---|---|---|
1 | int indexOf(int ch) | 它返回给定 char 值的索引位置 |
2 | int indexOf(int ch, int fromIndex) | 它返回给定 char 值和索引的索引位置 |
3 | int indexOf(String substring) | 它返回给定子字符串的索引位置 |
4 | int indexOf(String substring, int fromIndex) | 它返回给定子字符串和索引的索引位置 |
参数
ch:一个字符值,例如 'a'
fromIndex:返回char值或子字符串的索引的索引位置。
substring:在此字符串中要搜索的子字符串。
返回值
所搜索的字符串或字符的索引。
内部实现
public int indexOf(int ch) {
return indexOf(ch, 0);
}
Java String indexOf()方法示例
文件名:IndexOfExample.java
public class IndexOfExample{
public static void main(String args[]){
String s1="this is index of example";
//传递子串
int index1=s1.indexOf("is");//返回子字符串的索引
int index2=s1.indexOf("index");//返回索引子字符串的索引
System.out.println(index1+" "+index2);//2 8
//使用 from 索引传递子字符串
int index3=s1.indexOf("is",4);//返回第 4 个索引之后的子字符串的索引
System.out.println(index3);//5 即另一个索引是
//传递字符值
int index4=s1.indexOf('s');//返回 s 字符值的索引
System.out.println(index4);//3
}}
输出:
2 8
5
3
我们观察到当找到搜索的字符串或字符时,该方法返回一个非负值。如果未找到字符串或字符,则返回-1。我们可以使用这个属性来找到给定字符串中存在的字符的总数。观察下面的例子。
文件名:IndexOfExample5.java
public class IndexOfExample5
{
// 主方法
public static void main(String argvs[])
{
String str = "Welcome to JavaTpoint";
int count = 0;
int startFrom = 0;
for(; ;)
{
int index = str.indexOf('o', startFrom);
if(index >= 0)
{
// 找到匹配项。因此,增加计数
count = count + 1;
// 开始查找搜索到的索引
startFrom = index + 1;
}
else
{
//这里index的值为-1。因此,终止循环
break;
}
}
System.out.println("In the String: "+ str);
System.out.println("The 'o' character has come "+ count + " times");
}
}
输出:
In the String: Welcome to JavaTpoint
The 'o' character has come 3 times
Java String indexOf(String substring)方法示例
该方法将子字符串作为参数,并返回子字符串的第一个字符的索引。
文件名:IndexOfExample2.java
public class IndexOfExample2 {
public static void main(String[] args) {
String s1 = "This is indexOf method";
// 传递子字符串
int index = s1.indexOf("method"); //返回这个子串的索引
System.out.println("index of substring "+index);
}
}
输出:
index of substring 16
Java String indexOf(String substring, int fromIndex)方法示例
该方法将子字符串和索引作为参数,并返回在给定fromIndex之后第一次出现的第一个字符的索引。
文件名:IndexOfExample3.java
public class IndexOfExample3 {
public static void main(String[] args) {
String s1 = "This is indexOf method";
// 传递子字符串和索引
int index = s1.indexOf("method", 10); //返回这个子串的索引
System.out.println("index of substring "+index);
index = s1.indexOf("method", 20); // 如果没有找到子串则返回 -1
System.out.println("index of substring "+index);
}
}
输出:
index of substring 16
index of substring -1
Java String indexOf(int char, int fromIndex)方法示例
该方法将字符和索引作为参数,并返回在给定fromIndex之后第一次出现的第一个字符的索引。
文件名:IndexOfExample4.java
public class IndexOfExample4 {
public static void main(String[] args) {
String s1 = "This is indexOf method";
// 从中传递字符和索引
int index = s1.indexOf('e', 12); //返回这个字符的索引
System.out.println("index of char "+index);
}
}
输出:
index of char 17