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();
}
}
}
这里'obj'将调查'str2',但不会采用常见字符。这是obj每次检查str2中是否存在任何常见字符,但在那里,不会显示常见的匹配字符。
答案 0 :(得分:3)
问题:您正在检查character
而不是String
。
解决方案:您需要在String
内查看是否包含给定的Character
。
替换它:
if(obj.ToString().Contains(str2))
用这个:
if(str2.Contains(obj.ToString()))
完成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();
}
}
}
答案 1 :(得分:2)
只是另一种解决方案..虽然可能性能明显不好......但更小:
var str1 = "fire";
var str2 = "hire";
var common = str1.Intersect(str2);
foreach (var c in common)
Console.WriteLine(c); // "i", "r", "e"
答案 2 :(得分:0)
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;
}
答案 3 :(得分:-1)
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();
}