Difficulty: Easy
Correct Answer: String str = "She sells sea shells on the sea-shore"; int i, j; i = str.IndexOf("s"); j = str.IndexOf("s", i + 1);
Explanation:
Introduction / Context:
Locating the second occurrence of a character in a string is a standard string manipulation problem. In C#.NET, the IndexOf
method is heavily used to search for substrings or characters, and it has an overload that accepts a starting index. This makes it possible to find subsequent occurrences of a character.
Given Data / Assumptions:
's'
.S
at the beginning is not the same as lowercase 's'
.
Concept / Approach:
The proper approach is to find the first occurrence using IndexOf("s")
. Then, to locate the second occurrence, use the overload IndexOf("s", i + 1)
, which searches the string starting from the next index position after the first match.
Step-by-Step Solution:
Verification / Alternative check:
A manual scan of the string shows lowercase s at positions 6 (in "sells") and 10 (in "sea"). The code correctly returns index 10 for the second occurrence.
Why Other Options Are Wrong:
(a) SecondIndexOf
does not exist in .NET. (b) FirstIndexOf
is not a valid method. (d) LastIndexOf
finds the last occurrence, not the second. (e) Mixing uppercase and lowercase S incorrectly addresses the wrong character.
Common Pitfalls:
Forgetting that strings are zero-indexed or confusing uppercase and lowercase letters. Another frequent mistake is not incrementing the start index, which would simply return the same first occurrence again.
Final Answer:
String str = "She sells sea shells on the sea-shore"; int i, j; i = str.IndexOf("s"); j = str.IndexOf("s", i + 1);
Discussion & Comments