java indexof查找中文_在 Java 中如何使用 indexOf 和 lastIndexOf 方法在字符串中查找字符索引?...

indexOf 方法返回字符串中指定字符首次出现的索引。如果在字符串中找不到该字符,则返回 -1。

String str = "Search character";

/*

* The indexOf method only returns the

* index of the first occurrence of the character

*/

//will print 1, that is position 2 in the string

System.out.println( str.indexOf('e') );

//will print -1, as character z is not present in the string

System.out.println( str.indexOf('z') );

输出:

1

-1

默认的 indexOf 方法从索引 0 开始搜索字符。也可以用重载的 indexOf(char ch,int startIndex) 方法从指定位置开始搜索字符。

String str = "Search character";

/*

* this will start searching for a character 'e'

* from index 2 i.e. position 3 in the string

*/

//will print 14, that is position 15 in the string

System.out.println( str.indexOf('e', 2) );

输出:

14

同样,要搜索字符在字符串中最后一次出现的索引,可使用 lastIndexOf 方法。

String str = "Search character";

/*

* The lastIndexOf method searches the string

* backwards for a given character

*/

//this will print 14, i.e. position 15 in the string

System.out.println( str.lastIndexOf('e') );

/*

* you can also specify the index

* you want to start searching from

*/

/*

* this will print 1, because it will start searching

* for character 'e' from index 13 in the backward

* direction

*/

System.out.println( str.lastIndexOf('e', 13) );

输出:

14

1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值