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⽅法,检索字符串的位置
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";
字符串常量池的位置index = mail.indexOf("@");
if(index>0&&index<mail.length()-1){
System.out.println("是邮箱");
}else{
System.out.println("不是邮箱");
}
}
}
#运⾏结果为
以上这篇java 查字符串所在的位置代码就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。