How to find a letter in a string?

Asked

Viewed 1,980 times

1

How can I test if a letter (stored in a variable) is contained in a word? ex:

palavra = "palavra"
escolha = "a"

output

The word has 3 letters "a" in the word.... or

  • Hello Eliezer, could you show us what you are trying to do? A code would help the community a lot to help you.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

3 answers

3

I’m not a big fan of Regex, but Ruby encourages not having a very simple solution to this and having specific syntax for regular expressions, so I think the most appropriate.

palavra = "palavra"
escolha = "a"
contagem = palavra.scan(/(?=#{escolha})/).count
puts "A palavra tem #{contagem} letras 'a' na palavra"

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

2

A very readable format would be to use the character array that any String offers united with a count:

lookup_char = 'a'
'abcd abc ab a'.chars.count {|c| c == lookup_char} # => 4

1

If you just want to know if it includes the lyrics:

"palavra".include?("a")

If you want the number of times it appears:

"palavra".count("a")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.