StringBuilder search with indexOf and lastIndexOf
In this chapter you will learn:
Search a string inside a StringBuilder
We can search a StringBuilder with the following two methods.
int indexOf(String str)
Returns the index of the first occurrence of the specified substring.int indexOf(String str, int fromIndex)
Returns the index of the first occurrence of the specified substring, starting at the specified index.
public class Main {
public static void main(String[] argv) {
StringBuilder sb = new StringBuilder();
sb.append("java2s.com");
// ja va 2 s .c o m
int index = sb.indexOf("com");
System.out.println(index);
}
}
The output:
Search a StringBuilder from the end
The following two methods search a substring within StringBuilder from the end.
int lastIndexOf(String str)
returns the index of the rightmost occurrence of the specified substring.-
int lastIndexOf(String str, int fromIndex)
returns the index of the last occurrence of the specified substring.
public class Main {
/*jav a 2 s . c om*/
public static void main(String[] arg) {
StringBuilder phrase = new StringBuilder("one two three four");
int position = phrase.lastIndexOf("three");
System.out.println(position);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » String