Give the output of the following string functions :
(i) “MISSISSIPPI”.indexOf(‘S’) + “MISSISSIPPI”.lastIndexOf(‘I’)
(ii) “CABLE”.compareTo(“CADET”)
Solution
TC++ #4235
(i) “MISSISSIPPI”.indexOf(‘S’) + “MISSISSIPPI”.lastIndexOf(‘I’)
“MISSISSIPPI”.indexOf(‘S’) would be 2 (first index where ‘S’ is found)
“MISSISSIPPI”.lastIndexOf(‘I’) = 10 (last index where ‘I’ is found)
Summing both would give 12
(ii) “CABLE”.compareTo(“CADET”)
Here the mismatch would occur at index 2 as B is different from D. Now since first string’s mismatched character is smaller so answer would be negative. To get the answer we will subtract ascii of B from ascii of D which would be (66-68) . So the answer would be -2 .