好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

基于Java中字符串indexof() 的使用方法

java中 字符串 中子串的查找共有四种方法( indexof ())

indexof 方法返回一个整数值,指出 string 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。

如果 startindex 是负数,则 startindex 被当作零。如果它比最大的字符位置索引还大,则它被当作最大的可能索引。

java中字符串中子串的查找共有四种方法,如下:

1、int indexof(string str) :返回第一次出现的指定子字符串在此字符串中的索引。

2、int indexof(string str, int startindex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。

3、int lastindexof(string str) :返回在此字符串中最右边出现的指定子字符串的索引。

4、int lastindexof(string str, int startindex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。

?

1

2

3

4

5

6

7

8

9

10

11

12

public class test {

  public static void main(string[] args) {

   string s = "xxccxxxxx" ;

   // 从头开始查找是否存在指定的字符   //结果如下

   system.out.println(s.indexof( "c" ));  //2

   // 从第四个字符位置开始往后继续查找,包含当前位置

   system.out.println(s.indexof( "c" , 3 )); //3

   //若指定字符串中没有该字符则系统返回-1

   system.out.println(s.indexof( "y" ));  //-1

   system.out.println(s.lastindexof( "x" )); //6

  }

}

虽然简单,我就做个笔记。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

private static void testindexof() {

  string string = "aaa456ac" ;

 

  //查找指定字符是在字符串中的下标。在则返回所在字符串下标;不在则返回-1.

  system.out.println(string.indexof( "b" )); //indexof(string str);返回结果:-1,"b"不存在

 

  // 从第四个字符位置开始往后继续查找,包含当前位置

  system.out.println(string.indexof( "a" , 3 )); //indexof(string str, int fromindex);返回结果:6

 

  //(与之前的差别:上面的参数是 string 类型,下面的参数是 int 类型)参考数据:a-97,b-98,c-99

 

  // 从头开始查找是否存在指定的字符

  system.out.println(string.indexof( 99 )); //indexof(int ch);返回结果:7

  system.out.println(string.indexof( 'c' )); //indexof(int ch);返回结果:7

 

  //从fromindex查找ch,这个是字符型变量,不是字符串。字符a对应的数字就是97。

  system.out.println(string.indexof( 97 , 3 )); //indexof(int ch, int fromindex);返回结果:6

  system.out.println(string.indexof( 'a' , 3 )); //indexof(int ch, int fromindex);返回结果:6

 

  //这个就是灵活运用string类提供的方法,拆分提供的字符串。

  //string s = "d:\\android\\sdk\\add-ons";

  //system.out.println(s);

  //while (s.lastindexof("\\") > 0) {

  // s = s.substring(0, s.lastindexof("\\"));

  // system.out.println(s);

  //}

}

上面代码的运行结果如下:

以上这篇基于java中字符串indexof() 的使用方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/qq_27093465/article/details/51832189

查看更多关于基于Java中字符串indexof() 的使用方法的详细内容...

  阅读:45次