R Program to Compare two Strings

Example 1: Using toupper() to Compare Two Strings in R

# create two strings
string1 <- "R Programming"
string2 <- "R Programming"
 
# compare both strings
result <- toupper(string1) == toupper(string2)
 
print(result)

# Output: [1] TRUE

In the above example, two strings are compared. Here,

  1. The toupper() function converts all the string characters to uppercase.
  2. == is used to check if both the strings are the same.

Note: You can also use the tolower() function to convert all the strings to lowercase and perform the comparison.


Example 2: Compare Two Strings Using identical()

str1 <- "Data Science"

str2 <- "Data scientist"

# using identical() to compare two strings
identical(tolower(str1), tolower(str2)) 

# Output : [1] FALSE

Here, we have passed the identical() function to compare two strings: str1 and str2.

Inside identical(), we have passed two strings and converted to lowercase using tolower().

Since, "Data Science" and "Data Scientist" are two different strings, the method returns FALSE.