携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第23天,点击查看活动详情
java 中indexof():
指定字符在此实例中的第一个匹配项的索引并从指定字符位置开始搜索,检查指定数量的字符位置。其实就是在字符串中,对其子串的查找。
Java中提供了四中查找方法: 1、int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。
2、int indexOf(String str, intstartIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。
3、int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。
4、intlastIndexOf(String str, int startIndex):从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。
package com.example.democrud.democurd.controller;
public class indexof {
public static void main(String[] args) {
String s = "yanwenchaoyan";
// 从头开始查找是否存在指定的字符
//如不存在则为 -1 ,存在则显示下标位置 例如-- (0,1,2,3)
int le = s.indexOf("l");
int les = s.indexOf("n");
System.out.println("yanwenchao 的不存在则为是"+le);
System.out.println("yanwenchao的存在的下标为"+les);
System.out.println("---------------------------------------");
// 从第四个字符位置开始往后继续查找,包含当前位置,前面的就过滤掉
int i = s.indexOf("y", 3);
System.out.println("yanwenchao的下标位置是"+i);
System.out.println("---------------------------------------");
String s1 = "01234560123456";
int ls =s1.indexOf("123");
int lss = s1.lastIndexOf("123");
//反方向
int lsss=s1.lastIndexOf("123",4);
System.out.println("下标地址"+ls);
System.out.println("下标地址"+lss);
System.out.println("下标地址"+lsss);
System.out.println("---------------------------------------");
}
}
运行结果
yanwenchao 的不存在则为是-1
yanwenchao的存在的下标为2
---------------------------------------
yanwenchao的下标位置是10
---------------------------------------
下标地址1
下标地址8
下标地址1
---------------------------------------
注意:指定了索引位置之后,他或从索引后面开始进行查询(下标 0,1,2,…),返回下标值; 具体理解请看demo;
获取动态数组元素的索引:
如果我们想获得最后一次出现 Runoob 的位置,我们可以使用 lastIndexOf() 方法。
public static void main(String[] args){
// 创建一个数组
ArrayList<String> sites = new ArrayList<>();
sites.add("Google");
sites.add("Runoob");
sites.add("Taobao");
System.out.println("网站列表: " + sites);
// 查找位置索引值为 Runoob 的元素 存在他的下标为1,则返回1
//针对新手好理解(Google==>0(下标),Runoob==>1(下标),Taobao==>2(下标)) 故返回 1
//则数组下标为1
int position1 = sites.indexOf("Runoob");
System.out.println("Runoob 的索引位置: " + position1);
// 查找位置索引值为 Weibo 的元素 不存在返回-1
int position2 = sites.indexOf("Weibo");
System.out.println("Weibo 的索引位置: " + position2);
}
运行结果是
网站列表: [Google, Runoob, Taobao]
Runoob 的索引位置: 1
Weibo 的索引位置: -1
lastIndexOf
lastIndexOf() 方法返回指定元素在动态数组中最后一次出现的位置。
public static void main(String[] args){
// 创建一个数组
ArrayList<String> sites = new ArrayList<>();
//Runoob 存在2个 下面可得出第二次出现的位置也就是最后一次的位置
sites.add("Google");
sites.add("Runoob");
sites.add("Taobao");
sites.add("Runoob");
System.out.println("网站列表: " + sites);
// 获取 Runoob 最后一次出现的位置
int position1 = sites.lastIndexOf("Runoob");
System.out.println("Runoob 最后出现的位置: " + position1);
// Wiki 不在 arraylist 中
// 返回 -1
int position2 = sites.lastIndexOf("Wiki");
System.out.println("Wiki 最后出现的位置: " + position2);
}
}
加油把! 好好学习天天向上; 哈哈