java indexof(char),Java字符串indexOf()

本文概述

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

内部实施

public int indexOf(int ch) {

return indexOf(ch, 0);

}

签名

Java中有4种indexOf方法。下面给出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值, 即单个字符, 例如’一种’

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值