Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether two strings are anagrams

Tags:

string

r

anagram

What is the most straightforward way to check whether two strings are anagrams? i.e. they share the same letters as well as number of occurrences of each these letters (and possibly other characters).

Something like this:

s1 = "elbow"
s2 = "below"

is_anagram(s1, s2)
# [1] TRUE
like image 787
Maël Avatar asked Dec 10 '25 21:12

Maël


1 Answers

One way to do it is:

s1 = "elbow"
s2 = "below"

is_anagram <- function(s1, s2){
  s1_sorted <- sort(strsplit(s1, "")[[1]])
  s2_sorted <- sort(strsplit(s2, "")[[1]])
  identical(s1_sorted, s2_sorted)
}

#> is_anagram(s1, s2)
#> [1] TRUE
like image 165
Maël Avatar answered Dec 13 '25 11:12

Maël



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!