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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Enjoy..!!
No comments:
Post a Comment