if-else to check if a character string contains a specific substring.
Last Updated :
06 Sep, 2023
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
main_string <- "I have an apple and a banana."
substring_to_check <- "apple"
if ( grepl (substring_to_check, main_string))
{
print ( "The string contains 'apple'." )
} else {
print ( "The string does not contain 'apple'." )
}
|
Output:
[1] "The string contains 'apple'."
Example 2: Checking if “mango” is present in the string
R
main_string <- "We are enjoying delicious fruits."
substring_to_check <- "mango"
if ( grepl (substring_to_check, main_string)) {
print ( "The string contains 'mango'." )
} else {
print ( "The string does not contain 'mango'." )
}
|
Output:
[1] "The string does not contain 'mango'."
Share your thoughts in the comments
Please Login to comment...