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 <- "Programiz"

value1 <- "miz"

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

value2 <- "grm"

# check if "grm" is present in "Programiz"
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 "Programiz", the function returns TRUE
  • "grm" is not present in "Programiz", the function returns FALSE

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community