Challenge your understanding of string handling functions with these carefully crafted questions covering manipulation, searching, replacement, and formatting of strings. This quiz is perfect for learners eager to enhance their skills in string operations and boost their practical coding abilities.
Which function is commonly used to find the index of the first occurrence of the substring 'cat' in the string 'concatenate'?
Explanation: The 'indexOf' function is designed to locate the position of a substring within a larger string, returning the index of its first occurrence. 'substring' is used to extract parts of a string, not to search. 'replace' substitutes occurrences of a substring, while 'split' divides a string into an array based on a delimiter. Therefore, 'indexOf' is the most appropriate for finding a substring's position.
What function should you use to change all instances of 'dog' to 'cat' in the string 'The dog chased another dog'?
Explanation: 'replaceAll' replaces every occurrence of the target substring in the input string, which is ideal for this scenario. 'startsWith' checks if the beginning of the string matches a value, not for replacement. 'concat' joins strings together, and 'trim' removes whitespace from the ends of a string. Only 'replaceAll' will change every 'dog' to 'cat' in the entire string.
If you want to separate the words in 'red,green,blue' into a list, which string function should you use with the comma as a delimiter?
Explanation: The 'split' function divides a string into an array or list based on a specified delimiter, which is the comma in this case. 'contains' checks for the existence of a substring, not for splitting. 'endsWith' verifies a string’s ending, and 'charAt' retrieves a character at a specific index. Among these, only 'split' can separate 'red,green,blue' into individual words.
Given the string ' apple pie ', which function effectively removes only the leading and trailing spaces but leaves the internal spaces intact?
Explanation: 'trim' removes whitespace from the start and the end of a string, while preserving spaces within the string. 'upperCase' changes the string to all uppercase letters but does not affect spaces. 'substring' extracts a part of the string by indices, and 'padEnd' pads the end with specified characters. Thus, 'trim' is the function that meets the requirement.
Which function can you use to check if two strings 'Sun' and 'sun' are equal, ignoring the case of the letters?
Explanation: 'equalsIgnoreCase' compares two strings for equality without considering letter case, which is ideal for checking 'Sun' and 'sun'. 'repeat' is for duplicating a string multiple times, 'match' is typically for regular expression matching, and 'slice' extracts a section of a string. Only 'equalsIgnoreCase' performs a case-insensitive comparison.