Open In App

if-else to check if a character string contains a specific substring.

Last Updated : 06 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In R Programming Language, we can use the if-else statement to check if a character string contains a specific substring. The if-else statement allows us to execute different code blocks based on a certain condition, in this case, whether the substring is present in the given string.

if-else statement

The if-else statement is a control structure in R used to make decisions based on a given condition.

Character strings

The if-else statement is a control structure in R used to make decisions based on a given condition.

Substring

A substring is a smaller sequence of characters that appears within a larger character string.

To check if a character string contains a specific substring, follow these steps:

  • Define the main character string.
  • Define the substring you want to check for.
  • Use the if-else statement to check if the substring is present in the main string.
  • Execute different code blocks based on the presence or absence of the substring.

Let’s consider a few examples to illustrate how to use the if-else statement in R to check for a specific substring.

Example 1: Checking if a string is present in the string

R




# Step 1: Define the main character string
main_string <- "I have an apple and a banana."
 
# Step 2: Define the substring to check for
substring_to_check <- "apple"
 
# Step 3: Use the if-else statement to check if the substring is present
if (grepl(substring_to_check, main_string))
{
  # Step 4a: If the substring is present, execute this block of code
  print("The string contains 'apple'.")
   
} else {
  # Step 4b: If the substring is not present, execute this block of code
  print("The string does not contain 'apple'.")
}


Output:

[1] "The string contains 'apple'."

Example 2: Checking if “mango” is present in the string

R




# Step 1: Define the main character string
main_string <- "We are enjoying delicious fruits."
 
# Step 2: Define the substring to check for
substring_to_check <- "mango"
 
# Step 3: Use the if-else statement to check if the substring is present
if (grepl(substring_to_check, main_string)) {
   
# Step 4a: If the substring is present, execute this block of code
  print("The string contains 'mango'.")
} else {
 
  # Step 4b: If the substring is not present, execute this block of code
  print("The string does not contain 'mango'.")
}


Output:

[1] "The string does not contain 'mango'."


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads