Java StringBuffer int lastIndexOf(String s,int srcindex)方法,带示例
StringBuffer类intlastIndexOf(Strings,intsrcindex)
包java.lang.StringBuffer.lastIndexOf(Strings,intsrcindex)中提供了此方法。
此方法用于返回将在StringBuffer对象中搜索的指定子字符串最后一次出现的索引,而srcindex(Searchingindex)是从其开始搜索的索引。
如果在给定的StringBuffer对象中找不到子字符串,则此方法返回-1。
语法:
int lastIndexOf(String s, int srcindex){
}参数:
我们仅在StringBuffer方法中传递两个对象,即字符串和搜索索引(srcindex)。在这里,字符串是我们要搜索的字符序列,而srcindex是开始搜索的索引。
返回值:
此方法的返回类型为int,这意味着该方法返回指定子字符串的最后一次出现的索引,该字符串将在StringBuffer对象中进行搜索,即index为整数形式,这就是返回类型为int的原因。
Java程序演示lastIndexOf(Strings,intsrcindex)方法的示例
情况1:intlastIndexOf(Strings,intsrcindex)方法如何与StringBuffer对象中的重复(多次)子字符串一起使用?
import java.lang.StringBuffer;
public class StringBufferClass {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer(" java.utilisapackageofJava ");
//使用lastIndexOf(Strings,intsrcindex)
//它将检索最后一次出现的索引
//来自StringBuffer对象的指定子字符串。
//后显示结果"i""",9 )i.e.
//搜索第9个索引"i" comes twice till the searching of 9th index in a
//搜索第9个索引stringbuffer object so it returns the index of
//搜索第9个索引last occurrence of "i" i.e. 9th index
//搜索第9个索引[ First index of "i" is 7th index and Second index of "i" is 9th]
System.out.println("The index of last occurrence of i is :" + sb.lastIndexOf("i", 9));
}
}输出结果
The index of last occurrence of i is :8
情况2:intlastIndexOf(Strings)方法如何在StringBuffer对象中没有重复的(即多次)子字符串的情况下工作?
import java.lang.StringBuffer;
public class StringBufferClass {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Javaispopularinthisworld ");
//搜索第9个索引use lastIndexOf(String s) it will retrieve
//搜索第9个索引the index of last occurrence of specified
//搜索第9个索引substring from the StringBuffer object .
//后显示结果"u")
//搜索第9个索引i.e. u comes once till 9th index in a stringbuffer
//搜索第9个索引object so it returns the index of last occurrence of u
//搜索第9个索引i.e. 9th index[ First and Last index of u is one and only one 9th position]
System.out.println("The index of last occurrence of u is :" + sb.lastIndexOf("u", 9));
}
}输出结果
The index of last occurrence of u is :9