软件编程
位置:首页>> 软件编程>> java编程>> java 查找字符串所在的位置代码

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

作者:csdn9_14  发布时间:2023-12-22 21:48:17 

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

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

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


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 查找字符串所在的位置代码

来源:https://blog.csdn.net/csdn9_14/article/details/53672003

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com