indexOf and String Search

Part of: Using Objects

Finding Characters and Substrings The indexOf method searches a String and returns the index of the first occurrence of a target. The target can be a single-character String (or char) or a longer substring. The -1 Convention The single most important rule: if the target is not present , indexOf returns -1 . Since no real index is negative, -1 is a safe "not found" signal. Always test for it: Searching From a Position A second form starts the search at a given index, letting you find later occurrences: By passing first + 1 as the start, you can step through every match in a loop. Combining With substring indexOf and substring pair naturally. To grab everything before the first space: Guard against -1 first; calling substring(0, -1) would throw an exception. Why This Matters Parsing text, splitting names, reading file paths, finding delimiters, relies on this search-then-slice pattern. Mastering the -1 check and the start-index overload makes you fluent at extracting structured data from raw Strings, a skill used constantly on the AP exam free-response questions.

Challenge: Extract First Name