If I understand your requirements correctly, what you need to do is find each character in string1 that exists in string2. For everyone character you find, remove all occurrences of it from both strings.
One option is to just iterate each character in the first string, checking if they are contained within the second string. This is fairly inefficient because it iterates each character of the original string rather than the string as it's being changed. So if the first string contains duplicate characters itself, it will iterate them but not do anything after the first pass.
Dim string1 As String = "horse"
Dim string2 As String = "donkey"
For Each c As Char In string1
If string2.Contains(c) Then
string1 = string1.Replace(c.ToString(), "")
string2 = string2.Replace(c.ToString(), "")
End If
Next
Another option is to use LINQ to find the intersection of the two strings. This would give you a distinct list of the common characters between the two strings.
Dim string1 As String = "horse"
Dim string2 As String = "donkey"
Dim ar() As Char = string1.Intersect(string2).ToArray()
For Each c As Char In ar
string1 = string1.Replace(c.ToString(), "")
string2 = string2.Replace(c.ToString(), "")
Next
Edit: In case you have strings that contain upper and lower case letters, you need to handle that manually since Replace()
doesn't.
You can check out this answer for a couple different ways to extend the capabilities of Replace()
. Or, if you aren't too worried about performance, just use ToUpper()
and ToLower()
.
For Each c As Char In string1
If string2.Contains(c.ToString().ToLower()) Or string2.Contains(c.ToString().ToUpper()) Then
string1 = string1.Replace(c.ToString().ToLower(), "")
string2 = string2.Replace(c.ToString().ToLower(), "")
string1 = string1.Replace(c.ToString().ToUpper(), "")
string2 = string2.Replace(c.ToString().ToUpper(), "")
End If
Next