C# 如何打印匹配字符数

C# 如何打印匹配字符数,c#,C#,我有以下代码: Console.WriteLine("Enter first word"); string word1 = Console.ReadLine(); Console.WriteLine("Enter a second word"); string word2 = Console.ReadLine(); int count = 0; foreach (char obj in word1) if (wo

我有以下代码:

  Console.WriteLine("Enter first word");
     string word1 = Console.ReadLine();

   Console.WriteLine("Enter a second word");
     string word2 = Console.ReadLine();


     int count = 0;
        foreach (char obj in word1)

          if (word2.Contains(obj.ToString()))
             {
                Console.WriteLine(obj);

                  count++;
             }
            Console.ReadLine();
它给我匹配的字符,但我只想打印匹配的字符数。有人能帮我吗


e、 g.如果输入为“bla”和“bar”,则输出为“2”,因为“b”和“a”是匹配的字符。

如果单词包含一个多次字符(例如单词1是car,单词2是banana),那么计数器的结果将是3,如果您不需要,可以使用intersect,它只返回出现在两个字符串中的字符,并且只返回一次

    string word1 = "bla";
    string word2 = "bar";
    Console.WriteLine(word1.Intersect(word2).Count());
循环解决方案:

 Console.WriteLine("Enter the first word");
 string word1 = Console.ReadLine();

 Console.WriteLine("Enter the second word");
 string word2 = Console.ReadLine();

 HashSet<char> processed = new HashSet<char>();

 int count = 0;

 foreach (char c in word1) 
   if (processed.Add(c))        // If c a new character  
     if (word2.IndexOf(c) >= 0) // and it's found within word2 
       count += 1;

 Console.WriteLine(count);
Console.WriteLine(“输入第一个单词”);
string word1=Console.ReadLine();
Console.WriteLine(“输入第二个单词”);
string word2=Console.ReadLine();
HashSet processed=新的HashSet();
整数计数=0;
foreach(word1中的字符c)
if(processed.Add(c))//如果c是一个新字符
if(word2.IndexOf(c)>=0)//并且它在word2中找到
计数+=1;
控制台写入线(计数);

在这里,我们只计算唯一字符,即,我们希望为
“abacus”
“缩写”
'a'
'b'
字符)获得
2

首先需要定义“重叠”。对于“abc”和“abdc”,预期产量是多少?另外,您的问题是否真的是此代码打印字符,而您只想打印计数?然后移除
WriteLine(obj)
并添加
WriteLine(count)
..?而不是
控制台。在循环完成后写入(obj)
控制台。写入(count)。您发布的代码没有发现重叠字符(打印时字符部分覆盖另一个字符),它查找另一个字符串中包含的字符。这就是为什么代码使用
Contains
对我来说,重叠是第一个字符串以子字符串结尾,第二个字符串以子字符串开头。这不是您的代码所做的。对于
“abacus”
“缩写”
的预期结果是什么?请注意,
a
b
会多次出现。