Home > Net >  Check whether two strings are anagrams
Check whether two strings are anagrams

Time:04-08

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

CodePudding user response:

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

CodePudding user response:

A simple way to achieve that:

library(tidyverse)

s1 = "elbow"
s2 = "below"

is_anagram <- function(s1, s2){
  identical(str_split(s1, "") %>% table, str_split(s2, "") %>% table)
}

is_anagram(s1, s2)

#> [1] TRUE

CodePudding user response:

You can try the code below

> length(do.call(setdiff, Map(utf8ToInt, list(s1, s2)))) == 0
[1] TRUE
  • Related