Java中,indexOf()与lastIndexOf()的区别?
时间: 2024-01-28 13:52:15 浏览: 23
在Java中,`indexOf()`和`lastIndexOf()`都是用于查找字符串中某个字符或子字符串的位置,但它们的区别在于:
- `indexOf()`方法返回字符串中第一个匹配子字符串的位置,如果没有匹配,则返回-1。
- `lastIndexOf()`方法返回字符串中最后一个匹配子字符串的位置,如果没有匹配,则返回-1。
举个例子,假设有一个字符串`str = "hello world"`,那么:
- `str.indexOf('l')`将返回2,因为第一个匹配的字符'l'出现在位置2。
- `str.lastIndexOf('l')`将返回9,因为最后一个匹配的字符'l'出现在位置9。
同时,这两个方法都可以接受一个字符串参数,表示要查找的子字符串,而不仅仅是单个字符。例如:
- `str.indexOf("wo")`将返回6,因为子字符串"wo"出现在位置6。
- `str.lastIndexOf("l")`将返回9,因为最后一个匹配的子字符串"l"出现在位置9。
相关问题
java indexof和lastindexof
Java中的indexOf和lastIndexOf方法都是用于查找字符串中某个字符或子字符串的位置。其中indexOf方法返回第一次出现的位置,而lastIndexOf方法返回最后一次出现的位置。这两个方法都可以接受一个起始位置参数,表示从哪个位置开始查找。如果没有找到,则返回-1。
引用:注意 lastIndexOf(“str”, index)方法,这里返回的是 从下标0开始,以index结尾(包含index下标)之间搜索最后一个字符或字符串下标。 。
引用:int indexOf(String str, int fromIndex):返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始 int lastIndexOf(String str):返回指定子字符串在此字符串中最右边出现处的索引 int lastIndexOf...。
引用:直接上代码: String s = "01234560123456"; int a = s.indexOf('1'); // 返回第一个字符1的下标 int b = s.indexOf("23"); // 返回第一个字符串“23”的下标 int c = s.indexOf('1',5); // 以下标5开始,返回第一个字符1的下标 int d = s.indexOf("23",5); // 以下标5开始,返回第一个字符串“23”的下标 System.out.println(a + " " + b + " " + c + " "+ d); 。
java中indexOf怎么用
indexOf是一个String类中的方法,用于查找一个字符或字符串在另一个字符串中出现的位置。它的用法如下:
1.查找单个字符的位置:
String str = "Hello World";
int index = str.indexOf('o');
System.out.println(index); // 4
2.查找字符串的位置:
String str = "Hello World";
int index = str.indexOf("World");
System.out.println(index); // 6
3.从指定位置开始查找:
String str = "Hello World";
int index = str.indexOf("l", 3);
System.out.println(index); // 3
4.查找最后一个字符或字符串的位置:
String str = "Hello World";
int index = str.lastIndexOf('o');
System.out.println(index); // 7
5.查找所有匹配的位置:
String str = "Hello World";
int index = str.indexOf('o');
while (index != -1) {
System.out.println(index);
index = str.indexOf('o', index + 1);
}
注意:indexOf返回的是第一次出现位置的索引,如果没有找到则返回-1。