Open In App

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

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:

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




# 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




# 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'."

Article Tags :