Common characters in two strings

Here I'm going to show how to compare two strings to find out how many characters are common in two strings. I create a method which take two strings as inputs and return the number of characters in the second String that are contained in the first string, in a one-to-one relationship.

static void Main(string[] args)
{
Console.WriteLine("Welcome the common character Finder!\nWrite your 1st word here :");
string firstWord = Console.ReadLine();
Console.WriteLine("2nd word :");
string secondtWord = Console.ReadLine();
try
{
int numberOfCharacters = compare(firstWord, secondtWord);
Console.WriteLine("Number of common characters: "+numberOfCharacters);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
}
public static int compare(String input1, String input2)
{
int[] c = new int[256];
for (int i = 0; i < 256; i++)
{
c[i] = 0;
}
for (int i = 0; i < input1.Length; i++)
{
c[input1[i]]++;
}
int total = 0;
for (int i = 0; i < input2.Length; i++)
{
if (c[input2[i]] > 0)
{
total++;
c[input2[i]]--;
}
}
return total;
}
view raw compare.cs hosted with ❤ by GitHub
That is all
Enjoy..!!



No comments:

Post a Comment