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

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

语法:stringobject.indexof(searchvalue,fromindex)

参数 描述

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

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

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

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

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

示例:

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 在 字符串中最后出现的位置

示例:

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方法,检索字符串的位置

d87f1ddedb09f853d5c59eafc846d55b.png

1160d55e26e0cfe86d8388fa80c9d2fd.png

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

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

}else{

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

}

}

}

#运行结果为

2435a1ab1b7d96929b0e14d834caadb2.png

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

希望与广大网友互动??

点此进行留言吧!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值