Which method is used to search for a substring ?
-
stringVariable.substring(subString)
-
stringVariable.find(subString)
-
stringVariable.indexOf(subString)
-
stringVariable.indexOf(charAt(0))
The indexOf() method searches for a substring within a string and returns the index of the first occurrence, or -1 if not found. The syntax is string.indexOf(substring). Options A and B use incorrect method names (substring, find), and option D incorrectly nests charAt(0) inside indexOf.
To answer this question, you need to understand the different methods used to search for a substring within a string.
Let's go through each option to understand why it is correct or incorrect:
Option A) stringVariable.substring(subString) - This option is incorrect because the substring method is used to extract a substring from a string based on the specified indices, not to search for a substring.
Option B) stringVariable.find(subString) - This option is incorrect because there is no find method in Java's String class. It might be a method available in a different programming language or library, but it is not applicable here.
Option C) stringVariable.indexOf(subString) - This option is correct. The indexOf method is used to search for the first occurrence of a substring within a string and returns the index of the substring if found. If the substring is not found, it returns -1.
Option D) stringVariable.indexOf(charAt(0)) - This option is incorrect because charAt(0) returns the first character of the string, not a substring. The indexOf method expects a substring as its parameter, not an individual character.
The correct answer is C) stringVariable.indexOf(subString). This option is correct because the indexOf method is used to search for a substring within a string.