Java字符串indexOf()
的Java字符串的indexOf()方法返回给定的字符数值或子字符串的索引。如果找不到,则返回-1。索引计数器从零开始。
Java中有4种indexOf方法。
方法 | 描述 | |
---|---|---|
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:char值,即单个字符,例如“ a”
fromIndex:从此处获取char值或子字符串的索引的索引位置
substring:要在此字符串中搜索的子字符串
返回
字符串的索引
Java String indexOf()方法示例
- public class IndexOfExample{
- public static void main(String args[]){
- String s1="this is index of example";
- //passing substring
- int index1=s1.indexOf("is");//returns the index of is substring
- int index2=s1.indexOf("index");//returns the index of index substring
- System.out.println(index1+" "+index2);//2 8
- //passing substring with from index
- int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index
- System.out.println(index3);//5 i.e. the index of another is
- //passing char value
- int index4=s1.indexOf('s');//returns the index of s char value
- System.out.println(index4);//3
- }}
2 8
5
3
Java String indexOf(String substring)方法示例
此方法将子字符串作为参数,并返回该子字符串的第一个字符的索引。
- public class IndexOfExample2 {
- public static void main(String[] args) {
- String s1 = "This is indexOf method";
- // Passing Substring
- int index = s1.indexOf("method"); //Returns the index of this substring
- System.out.println("index of substring "+index);
- }
- }
index of substring 16
Java字符串indexOf(String substring,int fromIndex)方法示例
此方法将子字符串和索引作为参数,并返回在给定fromIndex之后出现的第一个字符的索引。
- public class IndexOfExample3 {
- public static void main(String[] args) {
- String s1 = "This is indexOf method";
- // Passing substring and index
- int index = s1.indexOf("method", 10); //Returns the index of this substring
- System.out.println("index of substring "+index);
- index = s1.indexOf("method", 20); // It returns -1 if substring does not found
- System.out.println("index of substring "+index);
- }
- }
index of substring 16 index of substring -1
Java字符串indexOf(int char,int fromIndex)方法示例
此方法将char和index作为参数,并返回在给定fromIndex之后出现的第一个字符的索引。
- public class IndexOfExample4 {
- public static void main(String[] args) {
- String s1 = "This is indexOf method";
- // Passing char and index from
- int index = s1.indexOf('e', 12); //Returns the index of this char
- System.out.println("index of char "+index);
- }
- }
index of char 17