Searching For and Retrieving Substrings

int result = string1.indexOf(string2);
											int result = string1.indexOf(string2, 5);

In the first method shown, the value of result will contain the index of the first occurrence of string2 within string1. If string2 is not contained within string1, -1 will be returned.

In the second method shown, the value of result will contain the index of the first occurrence of string2 within string1 that occurs after the fifth character within string1. The second parameter can be any valid integer greater than 0. If the value is greater than the length of string1, a result of -1 will be returned.

Besides searching a string for a substring, there might be times when you know where a substring is that you are interested ...

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.