c# - 我如何检查两个字符串是否包含相同的字母

标签 c# regex

我目前正在完成一个 C# 编程挑战,我卡在了主要部分。应用程序必须取两个单词,看看它们是否包含相同的字母。我将如何检查 input1input2 是否包含相同的字母?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace Words_With_Enemies
{
    class Program
    {

        static string input1, input2;

        public void findLetters()
        {
            bool regexWord1 = Regex.IsMatch(input1, @"^[a-zA-Z]+$");
        }

        static void Main(string[] args)
        {

            Console.WriteLine("Please enter two words");
            input1 = Console.ReadLine();
            input2 = Console.ReadLine();

            Console.WriteLine("You have entered the following two words:");
            Console.WriteLine(input1);
            Console.WriteLine(input2);

            Console.ReadLine();

        }

     }
}

最佳答案

如果你想找到如果两个字符串中的所有字母都相同,那么你可以使用Except()来自 System.Linq 命名空间:

bool result = input1.Except(input2).Any();

如果它们不包含相同的字母,它将返回 true

此类输入的输出将是这样的:

Apples, Apple => True
Apples, Banana => True
Apple, Alep => False
Apple, Apple => False

更新:

如果你想查找两个字符串中是否包含任何字母,那么你可以使用Intersect() :

bool result = input1.Intersect(input2).Any();

如果它们包含至少一个相同的字母,它将返回 true。 此类输入的输出将是这样的:

此类输入的输出将是这样的:

Apples, Apple => True
Apples, Banana => True
Apple, Alep => True
Apple, Onion => False


其他详细信息:
如果您想不区分大小写查找结果,那么您可以将这两个代码更改为:

bool result = input1.ToLowerInvariant().Except(input2.ToLowerInvariant()).Any();
bool result = input1.ToLowerInvariant().Intersect(input2.ToLowerInvariant()).Any();

关于c# - 我如何检查两个字符串是否包含相同的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29193968/

相关文章:

c# - 快速发送进程间信号

c# - MSBUILD 与 VS2008 构建之间的差异

java - 使用可选单词验证重复的精确匹配模式

javascript - 如何在javascript中使用正则表达式只获取数字

python - 如何拆分句子,只让 ascii 字符

c# - MVC 模型绑定(bind)问题 - 对象列表

c# - 我可以向调用基类中 protected 方法的派生类添加扩展方法吗?

c# - 如何将 "generic"C# 集合公开给 COM

regex - 如何动态构建 Perl 正则表达式?

php - 这个正则表达式在寻找什么