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

Ruby Example: Write a program to get the index of the substring in a string.
Submitted by Nidhi, on January 02, 2022

Problem Solution:

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

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 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.

Ruby Strings Programs »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.