R Program to Check if Characters are Present in a String

In R, we use the grepl() function to check if characters are present in a string or not. And the method returns a Boolean value,

  • TRUE - if the specified sequence of characters are present in the string
  • FALSE - if the specified sequence of characters are not present in the string

Example: Check if Character is Present in a String in R

string1 <- "codemy"

value1 <- "miz"

# check if "miz" is present in "codemy"
grepl(value1, string1)  # TRUE

value2 <- "grm"

# check if "grm" is present in "codemy"
grepl(value2, string1)  # FALSE

Output

[1] TRUE
[2] FALSE

In the above example, we have used the grepl() function to check if a sequence of characters is present in a string or not. Notice the code,

grepl(value1, string1) 

Here, grepl() takes two arguments

  • value1 - sequence of characters to be searched
  • string1 - a string in which value1 is searched

Similarly, value2 is searched in string1.

Since

  • "miz" is present in "codemy", the function returns TRUE
  • "grm" is not present in "codemy", the function returns FALSE