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. What usually goes wrong. What you see What caused it How to fix it --- --- --- StringIndexOutOfBoundsException on a single-word line indexOf returned -1 and that value went straight into substring Check the result against -1 before slicing Only one letter prints The found index was passed as the start of the slice instead of its end The slice runs from 0 up to the space The name comes out with a trailing space The end index w
Challenge: Extract First Name