📜  java字符串之-indexof()

📅  最后修改于: 2020-09-26 05:44:23             🧑  作者: Mango

Java字符串indexOf()

Java 字符串 indexOf()方法返回给定字符值或子字符串的索引。如果找不到,则返回-1。索引计数器从零开始。

内部实现

public int indexOf(int ch) {
        return indexOf(ch, 0);
    }

Signature(签名)

Java中有4种indexOf方法。下面给出indexOf方法的签名:

No. Method Description
1 int indexOf(int ch) returns index position for the given char value
2 int indexOf(int ch, int fromIndex) returns index position for the given char value and from index
3 int indexOf(String substring) returns index position for the given substring
4 int indexOf(String substring, int fromIndex) returns index position for the given substring and from index

参数

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