Last active
November 29, 2017 17:41
-
-
Save dharshan/da9605b5a34a271b114d981f93220c5e to your computer and use it in GitHub Desktop.
Substring in String in Ruby using each_with_index loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 | |
Enter a String | |
bengaluru | |
Enter a Sub String | |
uru | |
=> Present | |
2 | |
Enter a String | |
bengaluru | |
Enter a Sub String | |
ban | |
=> NOT Present | |
3 | |
Enter a String | |
bengaluru at 9am | |
Enter a Sub String | |
at 9 | |
=> Present | |
4 | |
Enter a String | |
Enter a Sub String | |
at | |
=> Not Present | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Substring in String using each_with_index loop | |
p 'Enter a String' | |
str = gets.chomp | |
p 'Enter a Sub String' | |
sub_str = gets.chomp | |
def substring_present?(str, sub_str) | |
str_ar = str.split('') # convert string to char array | |
sub_str_ar = sub_str.split('') | |
str_ar.each_with_index do |val, index| | |
# if starting char of substring is equal to char in string | |
# then check for next substring len of char matches to substring | |
if val == sub_str_ar[0] && str[index..index + (sub_str_ar.count - 1)] == sub_str | |
return true | |
end | |
end | |
return false | |
end | |
if substring_present?(str, sub_str) | |
p 'Substring Present' | |
else | |
p 'Substring NOT Present' | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment