String Search
Sometimes we also want to go the other way – get back the index of a character or piece within a
string. We can do this with the indexOf command. Here is an example:
String s = "cake";
//has value 1
int index = s.indexOf("a"); Notice that we get back 1, which is the index of “a” in the string “cake”. We can also search for a bigger piece of a string:
String s = "cake";
//has value 2
int bigIndex = s.indexOf("ke"); Now we get back 2, because the piece “ke” starts at index 2 within “cake”. Here are some more examples:
String second = "hello";
//has value 2
int find1 = second.indexOf("l");
//has value -1
int find2 = second.indexOf("x"); Notice that “l” appears twice in “hello”, but we get back the index of the FIRST “l”. Also, when we search for something that’s not in the string (like “x”), we get back -1.