ADVERTISEMENT
ADVERTISEMENT

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 »


ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.