我目前正在完成一个 C# 编程挑战,我卡在了主要部分。应用程序必须取两个单词,看看它们是否包含相同的字母。我将如何检查 input1
和 input2
是否包含相同的字母?
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/