当前位置: 移动技术网 > IT编程>开发语言>Java > java 查找字符串所在的位置代码

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

2020年09月13日  | 移动技术网IT编程  | 我要评论
使用了 string 类的 indexof() 方法在字符串中查找子字符串出现的位置,如过存在返回字符串出现的位置(第一位为0),如果不存在返回 -1。方便判断和截取字符串!语法:stringobje

使用了 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.com";
 index = mail.indexof("@");
 if(index>0&&index<mail.length()-1){
  system.out.println("是邮箱");
 }else{
  system.out.println("不是邮箱");
 }
 
 }
}

#运行结果为

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网