Q:

Ruby program to get the index of the substring in a string

belongs to collection: Ruby Strings Programs

0

In this program, we will create two strings and get the index of the specified substring in the string using the index() method.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

# 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 strsubstr1substr2 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

total answers (1)

Ruby Strings Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Ruby program to pad a string with 0\'s on lef... >>
<< Ruby program to check a string contains a specifie...