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

Comments

11 Jan 2010 - 9:38am by Morf3usz (not verified)

Great! Thanks for this advice, it was very useful for me!

20 Jan 2010 - 12:59am by Anonymous (not verified)

useful for starters

25 Jan 2010 - 2:12am by Anonymous (not verified)

Very good one for beginners

1 Feb 2010 - 12:05am by rast (not verified)

shouldn't index = string.indexOf("dam"); be 2?

1 Feb 2010 - 10:11pm by patrick

Yes, you're right. I just corrected it. Thanks.

23 Feb 2010 - 9:21am by Anonymous (not verified)

Very useful for beginners

10 Mar 2010 - 3:05pm by Dave (not verified)

Thanks so much for this!

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.