Searching a String for a Character or a Substring
See also Quintessential Regular Expression Search Program.
String string = "madam, i am Adam";
// Characters
// First occurrence of a c
int index = string.indexOf('a'); // 1
// Last occurrence
index = string.lastIndexOf('a'); // 14
// Not found
index = string.lastIndexOf('z'); // -1
// Substrings
// First occurrence
index = string.indexOf("dam"); // 2
// Last occurrence
index = string.lastIndexOf("dam"); // 13
// Not found
index = string.lastIndexOf("z"); // -1
Great! Thanks for this advice, it was very useful for me!
useful for starters
Very good one for beginners
shouldn't index = string.indexOf("dam"); be 2?
Yes, you're right. I just corrected it. Thanks.
Very useful for beginners
Thanks so much for this!