Compare two strings without taking into account the position of the words that compose it

Viewed 52

I know that, if

s1 <- "string"
s2 <- "String"

the comparison can be done as follows:

# Case-sensitive check
s1 == s2

# Case-insensitive check
tolower(s1) == tolower(s2)

What I have in mind, however, is a different kind of comparison:

s1 <- "John Smith"
s2 <- "Smith John"

If I apply previous code to this example, I obtain FALSE as result. But these two strings are formed by the same words, and I would like to have a comparison that gives, for this example, TRUE.

3 Answers

We create a function to split up the string by the space (strsplit), then unlist, sort, get the unique elements, paste them together again.

f1 <- function(x) toString(unique(sort(unlist(strsplit(tolower(x), " ")))))
f1(s1) == f1(s2)
#[1] TRUE

NOTE: ASCII codes for upper case letters (65 to 90) and lower case letters (97 to 122) are represented by different numbers). So, we need to make it to a standard case for comparison

Using utf8ToInt :

check_string <- function(s1, s2) {
     sum(utf8ToInt(tolower(s1))) == sum(utf8ToInt(tolower(s2)))
}

check_string("string", "string")
#[1] TRUE
check_string("string", "String")
#[1] TRUE
check_string("John Smith", "Smith John")
#[1] TRUE

These String are basically anagram of each other. You can check for it by storing both string in map and compare both map.

dict(collection.Counter(S1) == dict(collection.Counter(S2)

Related