java 查找字符串所在的位置代码

2025-05-29 0 36

使用了 String 类的 indexOf() 方法在字符串查找字符串出现的位置,如过存在返回字符串出现的位置(第一位为0),如果不存在返回 -1。方便判断和截取字符串

语法:stringObject.indexOf(searchvalue,fromindex)

参数 描述

searchvalue 必需。规定需检索的字符串值。

fromindex 可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是0到 – 1。如省略该参数, 则将从字符串的首字符开始检索。

该方法将从头到尾地检索字符串 stringObject,看它是否含有子串 searchvalue。开始检索的位置字符串的 fromindex 处或字符串的开头(没有指定 fromindex 时)。如果找到一个 searchvalue,则返回 searchvalue 的第一次出现的位置。stringObject 中的字符位置是从 0 开始的。

注释:indexOf() 方法对大小写敏感!

注释:如果要检索的字符串值没有出现,则该方法返回 -1。

示例:

?

1

2

3

4

5

6

7

8

9

10

11
public class SearchStringEmp {

public static void main(String[] args) {

String strOrig = "Hello World!Hello World!";

int intIndex = strOrig.indexOf("Hello");

if(intIndex == - 1){

System.out.println("没有找到字符串 Hello");

}else{

System.out.println("Hello 字符串位置:" + intIndex);

}

}

}

结果:

Hello 字符串位置: 0

注释:当字符串中多次出现相同的字符串时,此方法返回的值为第一次出现的位置的索引值。

lastIndexOf(Stringname):

我们可以通过lastIndexOf(Stringname) 来查找字符串 Stringname 在 字符串中最后出现的位置

示例:

?

1

2

3

4

5

6

7

8

9

10

11
public class SearchlastString {

public static void main(String[] args) {

String str = "Hello world!Hello World!";

int lastIndex = str.lastIndexOf("Hello");

if(lastIndex == - 1){

System.out.println("没有找到字符串 Hello");

}else{

System.out.println("Hello 字符串最后出现的位置: "+ lastIndex);

}

}

}

结果:

Hello 字符串最后出现的位置: 12

补充知识:Java编程——indexOf方法,检索字符串位置

java 查找字符串所在的位置代码

java 查找字符串所在的位置代码

?

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

28

29

30

31

32

33

34

35

36

37

38
package day01;

/**

* indexOf

* 检索字符串的位置

* @author Administrator

*

*/

public class StringDemo3 {

public static void main(String[] args){

// 0123456789012345

String str = "thinking in java";

int index = str.indexOf("java");

System.out.println("index:"+index);

/*

* indexOf(String str,int index)

* 查找给定字符串在当前字符串的位置

* 首先第一个参数要在当前字符串中找到

* 然后返回返回第一个字母所在的下标位置

*/

index = str.indexOf("in",5);

System.out.println("index:"+index);

index = str.indexOf("in",7);

System.out.println("index:"+index);

//返回最后一个in出现的位置

index = str.lastIndexOf("in");

System.out.println("index:"+index);

//email @

String mail = "123123123.com";

index = mail.indexOf("@");

if(index>0&&index<mail.length()-1){

System.out.println("是邮箱");

}else{

System.out.println("不是邮箱");

}

}

}

#运行结果为

java 查找字符串所在的位置代码

以上这篇java 查找字符串所在的位置代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

原文链接:https://blog.csdn.net/csdn9_14/article/details/53672003

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java 查找字符串所在的位置代码 https://www.kuaiidc.com/117244.html

相关文章

发表评论
暂无评论