Skip to content

Matching a character in a string

5 messages · Fabrice DELENTE, Paul Hiemstra, GlenB

#
Hello.

Sorry for this very basic question but I didn't find (of didn't understand)
the answer either in the help or in the online guide.

I have a string, let's say "hello". I want to know if there is some
character in it, let's say an 'o'.

I tried
but it gives NA (why??)

Thinking it may be a type problem, I tried
but it gives NA too (why???)

So how can I know if a given string contains a given char?

Thanks!
#
Fabrice DELENTE wrote:
try:

grep("o", "hello")

if the output is 1, there is a match. Note that the command is 
vectorized so:

grep("o", c("hello","pizza", "spam", "ogle"))

also works, picking out items 1 and 4 as containing an "o". The first 
argument to grep is a regular expression, and this can be very powerful. 
For example, which words start with a "p":

grep("^p", c("hello","pizza", "spam", "ogle"))

Check out more stuff on regular expressions on the internet. They are 
very powerful, but take some time to learn.

cheers,
Paul
#
Thanks, I hadn't noticed R has grep included!