Reputation: 33
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string str1="fire";
string str2 = "fire";
foreach(char obj in str1)
if(obj.ToString().Contains(str2))
{
Console.WriteLine(obj);
Console.ReadLine();
}
Console.ReadLine();
}
}
}
Here 'obj' will look into the 'str2' but will not take the common characters. That is obj each time checks if any common character exists in str2 but though there, will not display common match characters.
Upvotes: 1
Views: 9907
Reputation: 1
int commonCharacterCount(string s1, string s2)
{
int common = 0;
string toIterate = string.Empty;
if (s1.Length > s2.Length)
toIterate = s1;
else
{
toIterate = s2;
s2 = s1;
}
for (int i = 0; i < s1.Length; i++)
{
for (int j = 0; j < toIterate.Length; j++)
{
if (s1[i] == toIterate[j])
{
toIterate = toIterate.Remove(j, 1);
common++;
break;
}
}
}
return common;
}
Upvotes: 0
Reputation: 9
static void Main(string[] args)
{
string str1 = "fire";
string str2 = "hire ";
int count = 0;
foreach (char obj in str1)
if (str2.Contains(obj.ToString()))
{
Console.WriteLine(obj);
count++;
//Console.ReadLine();
}
Console.ReadLine();
}
Upvotes: -1
Reputation: 65087
Just another solution.. although probably just as bad performance wise.. but smaller:
var str1 = "fire";
var str2 = "hire";
var common = str1.Intersect(str2);
foreach (var c in common)
Console.WriteLine(c); // "i", "r", "e"
Upvotes: 4
Reputation: 26209
Problem : you are checking the character
instead of String
.
Solution: you need to check inside a String
whether it contains the given Character
or not.
Replace this:
if(obj.ToString().Contains(str2))
with this:
if(str2.Contains(obj.ToString()))
Complete SOlution:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string str1="fire";
string str2 = "fire";
foreach(char obj in str1)
if(str2.Contains(obj.ToString()))
{
Console.WriteLine(obj);
Console.ReadLine();
}
Console.ReadLine();
}
}
}
Upvotes: 3