[英]How would I check to see if two strings contain the same letters
我目前正在完成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();
}
}
}
如果要查找兩個字符串中的所有字母是否都相同 ,則可以使用System.Linq
命名空間中的Except()
:
bool result = input1.Except(input2).Any();
如果它們不包含相同的字母,它將返回true
。
這些輸入的輸出將如下所示:
蘋果,蘋果=> True
蘋果香蕉=>真
蘋果,阿勒普=> False
蘋果,蘋果=>錯誤
更新:
如果要查找兩個字符串中是否包含任何字母 ,則可以使用Intersect()
:
bool result = input1.Intersect(input2).Any();
如果它們至少包含一個相同的字母,它將返回true
。 這些輸入的輸出將如下所示:
這些輸入的輸出將如下所示:
蘋果,蘋果=> True
蘋果香蕉=>真
蘋果,阿勒普=> True
蘋果,洋蔥=>錯誤
其他細節:
如果要不區分大小寫地查找結果,則可以將兩個代碼更改為:
bool result = input1.ToLowerInvariant().Except(input2.ToLowerInvariant()).Any();
bool result = input1.ToLowerInvariant().Intersect(input2.ToLowerInvariant()).Any();
基本上,您想檢查兩個字符串是否排列。
static private bool isPermutation(string myString1, string myString2)
{
//If the strings are different lengths, they are not
//permutations.
if (myString1.Length != myString2.Length) return false;
//Create an array to count the number of each specific
//character in the strings.
int[] characterCount = new int[256];
int charIndex;
//Populate the array with default value 0.
for (int index = 0; index < 256; index++)
{
characterCount[index] = 0;
}
//Count the number of each character in the first
//string. Add the count to the array.
foreach (char myChar in myString1.ToCharArray())
{
charIndex = (int)myChar;
characterCount[charIndex]++;
}
//Count the number of each character in the second
//string. Subtract the count from the array.
foreach (char myChar in myString2.ToCharArray())
{
charIndex = (int)myChar;
characterCount[charIndex]--;
}
//If the strings are permutations, then each character
//would be added to our character count array and then
//subtracted. If all values in this array are not 0
//then the strings are not permutations of each other.
for (int index = 0; index < 256; index++)
{
if (characterCount[index] != 0) return false;
}
//The strings are permutations of each other.
return true;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.