首页 > 代码库 > java.lang.String.indexOf()用法

java.lang.String.indexOf()用法

java.lang.String.indexOf(char ch)

方法返回字符ch在指定字符串中第一次出现的下标索引位置

如果字符ch在指定的字符串中找不到,则返回-1

示例:

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {
  
    String str = "This is tanglc‘s cnblog";
    
    // returns the index of character s appear in the first time
    System.out.println("index of letter ‘s‘ = " 
    + str.indexOf(‘s‘)); 
      
    // returns -1 as character e is not in the string
    System.out.println("index of letter ‘e‘ = " 
    + str.indexOf(‘e‘));
  }
}

运行结果:

index of letter ‘s‘ = 3
index of letter ‘e‘ = -1