java中关于indexOf()函数和lastIndexOf()函数的使用方法

indexOf(String str) 函数和 lastIndexOf(String str) 函数都是String类中的函数,都是查找函数,查找str在字符串中出现的位置 一、indexOf(String str) 函数用法:

public class T {
          
   
	public static void main(String[] args) {
          
   
		String m = "Iamastudent";
		System.out.println(m.indexOf("I"));
		System.out.println(m.indexOf("Iam"));
		System.out.println(m.indexOf("i"));
	}
}

运行结果: 通过上述代码,了解到四个问题

  1. 查找指定序列在字符串中出现的位置是,原串中第一个字符的下标是0
  2. 如果查找的是一串字符串在原字符串中的位置时返回值是第一个字符在原字符中出现的位置
  3. 如果查找不到该串,返回值为-1
  4. 查找的字符串区分大小写
public class T {
          
   
	public static void main(String[] args) {
          
   
		String m = "I am a student";
		System.out.println(m.indexOf(" "));
		System.out.println(m.indexOf("a"));
		System.out.println(m.indexOf("I am"));
		System.out.println(m.indexOf("Iam"));
		System.out.println(m.indexOf("i"));	
	}
}

运行结果: 通过上述代码,了解到两个问题

  1. indexOf(String str) 函数返回的是原串中第一个字符出现的位置,字符包含空格等特殊符号
  2. 查找的字符串必须是原串的一个子串(子串的意思是包含特殊符号,必须是原串截取的一个小片段),否则返回-1,查找失败

二、lastIndexOf(String str) 函数用法

public class T {
          
   
	public static void main(String[] args) {
          
   
		String m = "HelloIloveyou";
		System.out.println(m.lastIndexOf("l"));
		System.out.println(m.lastIndexOf("h"));
		System.out.println(m.lastIndexOf("ll"));
	}
}

运行结果: 通过上述代码,了解到四个问题

  1. lastIndexOf(String str)函数从正序开始查找,原串中第一个字符的下标是0,查找到指定字符最后一次出现的位置
  2. 查找的字符串区分大小写
  3. 如果查找不到返回-1
  4. 查找的字符相同时,当做一个字符串处理,如查找"ll"是作为一个整体进行查找,返回第一个字符出现的下标
public class T {
          
   
	public static void main(String[] args) {
          
   
		String m = "Hello I love you";
		System.out.println(m.lastIndexOf("l"));
		System.out.println(m.lastIndexOf(" "));
		System.out.println(m.lastIndexOf("I love"));
		System.out.println(m.lastIndexOf("llove"));
	}
}

运行结果: 通过上述代码,了解到两个问题:

  1. lastIndexOf(String str) 函数返回的是原串中该字符出现的最后一次的位置,字符包含空格等特殊符号
  2. 查找的字符串必须是原串的一个子串(子串的意思是包含特殊符号,必须是原串截取的一个小片段),否则返回-1,查找失败
经验分享 程序员 微信小程序 职场和发展