StrugglingCoder
StrugglingCoder

Reputation: 5021

How to find characters that are there in one string and not there in another in C#?

I want to find distinct characters that are there in one string and not in another. Suppose firstString contains ABC and secondString contains BC now output op1 should contain 'characters that are distinctly there in the firstString but not in the secondString' i.e. A and op2 should contain 'characters that are distinctly there in the secondString but not in the firstString' i.e. in this case null. If firstString is 'SBG' and secondString is 'BANGALORE' op1 should be 'S' op2 should be 'ANLORE'

Upvotes: 0

Views: 1389

Answers (3)

Jonathon Chase
Jonathon Chase

Reputation: 9704

Adding on to the suggestion Karl-Johan Sjögren has given with using Enumerable.Except, you can very easily wrap this into an extension method.

public static class StringExtensions {
    public static string DistinctFrom(this string one, string two) {
        return new string(one.Except(two).ToArray());   
    }
}

//Usage. Given 'ABC' and 'BC' results 'A'
var distinctString = str1.DistrinctFrom(str2);

Pretty convenient if you're using this often, and lets you change you logic in one place if you need to.

Upvotes: 1

Karl-Johan Sjögren
Karl-Johan Sjögren

Reputation: 17577

This can easily be accomplished with the Enumerable.Except() method in Linq since a String also implements IEnumerable<char>.

    var str1 = "ABC";
    var str2 = "BC";

    var str3 = new string(str1.Except(str2).ToArray());
    var str4 = new string(str2.Except(str1).ToArray());


    var str5 = "SBG";
    var str6 = "BANGALORE";

    var str7 = new string(str5.Except(str6).ToArray());
    var str8 = new string(str6.Except(str5).ToArray());

Upvotes: 4

Lee
Lee

Reputation: 144136

Since you want the distinct characters you can use Except e.g.

using System.Linq;

"BANGALORE".Except("SBG")

Upvotes: 2

Related Questions