Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract distinct characters that differ between two strings

Tags:

string

r

I have two strings, a <- "AERRRTX"; b <- "TRRA" .

I want to extract the characters in a not used in b, i.e. "ERX"

I tried the answer in Extract characters that differ between two strings , which uses setdiff. It returns "EX", because b does have "R" and setdiff will eliminate all three "R"s in a. My aim is to treat each character as distinct, so only two of the three R's in a should be eliminated.

Any suggestions on what I can use instead of setdiff, or some other approach to achieve my output?

like image 684
Ricky Avatar asked Mar 23 '16 06:03

Ricky


People also ask

How do you find the uncommon characters in two strings in python?

Uncommonstring(s1,s2) /* s1 and s2 are two string */ Step 1: Convert both string into set st1 and st2. Step 2: use the intersection of two sets and get common characters. Step 3: now separate out characters in each string which are not common in both string.

How do you get non matching characters in a string?

Q: How to get the non-matching characters in a string? ​Find and print the uncommon characters of the two given strings in sorted order. Here uncommon character means that either the character is present in one string or it is present in other string but not in both.

How do you find unique characters in a string?

A unique string consists of characters that occur only once. To check for uniqueness, compare each character with the rest of the string. If a character is repeated, then the string is not unique.


1 Answers

A different approach using pmatch,

a1 <- unlist(strsplit(a, ""))
b1 <- unlist(strsplit(b, "")) 

a1[!1:length(a1) %in% pmatch(b1, a1)]

 #[1] "E" "R" "X"

Another example,

a <- "Ronak";b<-"Shah"

a1 <- unlist(strsplit(a, ""))
b1 <- unlist(strsplit(b, ""))
a1[!1:length(a1) %in% pmatch(b1, a1)]

# [1] "R" "o" "n" "k"
like image 146
Ronak Shah Avatar answered Oct 20 '22 18:10

Ronak Shah