The source code to get the index of the substring in a string is given below. The given program is compiled and executed successfully.
# Ruby program to get the index of
# substring from a string
str = "Hello India";
substr1="India";
substr2="World";
index = str.index(substr1);
if index != nil
print "String found at index ",index,"\n";
else
print "String not found\n";
end
index = str.index(substr2);
if index != nil
print "String found at index ",index,"\n";
else
print "String not found\n";
end
Output:
String found at index 6
String not found
Explanation:
In the above program, we created two string variables str, substr1, substr2 that are initialized with "Hello India", "India", "World". Then we used the index() method to check the string containing specified substring and print the appropriate message.
Program/Source Code:
The source code to get the index of the substring in a string is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created two string variables str, substr1, substr2 that are initialized with "Hello India", "India", "World". Then we used the index() method to check the string containing specified substring and print the appropriate message.
need an explanation for this answer? contact us directly to get an explanation for this answer