Description:
Obtaining Substrings
String s1 = "Welcome to Java";
Method Description
substring(beginIndex) Returns this string’s substring that begins with the character at the specified beginIndex
and extends to the end of the string, as shown in
e.g.
s1.substring(11); // Java
substring(beginIndex,endIndex) Returns this string’s substring that begins at the specified beginIndex
and extends to the character at index endIndex – 1
Note the character at endIndex is not part of the substring.
s1.substring(0,11); // Welcome to
Finding a Character or a Substring in a String
String s1 = "Welcome to Java";
Method Description
indexOf (ch) Returns the index of the first occurrence of ch in the string. Returns −1 if not matched.
s1.indexOf('W'); // 0
s1.indexOf('o'); // 4
indexOf(ch, fromIndex) Returns the index of the first occurrence of ch after fromIndex in the string.
Returns −1 if not matched.
s1.indexOf('o', 5); // 9
indexOf(s) Returns the index of the first occurrence of string s in this string. Returns −1
if not matched.
s1.indexOf("come"); // 3
indexOf(s, fromIndex) Returns the index of the first occurrence of string s in this string after fromIndex.
Returns −1 if not matched.
s1.indexOf("Java", 5); // 11
s1.indexOf("Java", 5); // -1
lastIndexOf(ch) Returns the index of the last occurrence of ch in the string. Returns −1 if not matched.
s1.lastIndexOf('W'); // 0
s1.lastIndexOf('o'); // 9
lastIndexOf(ch, fromIndex) Returns the index of the last occurrence of ch before fromIndex in this string.
Returns −1 if not matched.
s1.lastIndexOf('o', 5); // 4
lastIndexOf(s) Returns the index of the last occurrence of string s. Returns −1 if not matched.
s1.lastIndexOf("Java"); // 11
lastIndexOf(s, fromIndex) Returns the index of the last occurrence of string s before fromIndex. Returns −1 if not matched.
s1.lastIndexOf("Java", 5); // -1
Share this link via
Or copy link
























