开发手册 欢迎您!
软件开发者资料库

Java String indexOf() 方法

Java有一组可以用于字符串的内置方法。Java 字符串(String)操作常用操作,如字符串的替换、删除、截取、赋值、连接、比较、查找、分割等。本文主要介绍Java String indexOf() 方法。

Java 字符串方法

例如:

在字符串中搜索“wonhero”的首次出现:

String myStr = "c java python is wonhero and www.wonhero.com";System.out.println(myStr.indexOf("wonhero"));

1、定义和用法

indexOf()方法返回字符串中首次出现的指定字符的索引位置。

提示:使用lastIndexOf方法返回字符串中最后一次出现指定字符的位置。

2、调用语法

有4个indexOf()方法:

public int indexOf(String str)public int indexOf(String str, int fromIndex)public int indexOf(int char)public int indexOf(int char, int fromIndex)

3、参数说明

参数

描述

str

String值,表示要搜索的字符串

fromIndex

int值,表示从中开始搜索的索引位置

char

int值,表示单个字符,例如,'A'或Unicode值

4、方法说明

返回值:

int值,表示字符串中字符首次出现的索引,如果从未出现,则为-1

5、使用示例

例如:

在字符串中找到字母"java"的第一个匹配项,从位置10开始搜索:

public class Main {  public static void main(String[] args) {    String myStr = "c java python is wonhero and www.wonhero.com";
    System.out.println(myStr.indexOf("java", 10));  }}

Java 字符串方法