使用C#我试图在char数组中找到一个特定的单词。另外,我不希望同一个字母多次使用,即单词是'hello',我试图在一个随机字母数组中找到它,所以如果字母“l”用于随机数组之外字母,我不希望它再次被使用。字母数组中应该有另一个'l'用作“hello”中的第二个'l'。只是想要准确。一个简单的答案将非常有帮助。谢谢。
到目前为止,这是我的尝试。
public static char [] Note = "hello".ToCharArray();
public static char [] Newspaper = "ahrenlxlpoz".ToCharArray();
static void main(string[] args)
{
Array.Sort(Note);
Array.Sort(Newspaper);
if(Newspaper.Contains<Note>)
{
Console.Write("It should display the letters of Note found within Newspaper");
}
}
答案 0 :(得分:3)
我假设“包含”你的意思是报纸上有足够数量的来自每个字母的信件来弥补注意。例如,你需要至少两个l来组成单词“hello”。如果是这样,你需要基本上计算两个字符串中每个字母的数量,并确保Note中每个字母的数量小于或等于报纸中该字母的数量。
var dictNote = Note.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count());
var dictNews = Newspaper.GroupBy(c => c).ToDictionary(g => g.Key, g => g.Count());
bool contains = dictNote.All(x =>
dictNews.ContainsKey(x.Key) && x.Value <= dictNews[x.Key]);
答案 1 :(得分:-1)
试试这个:
public static char[] Note = "hello".ToCharArray();
public static char[] Newspaper = "ahrenlxlpoz".ToCharArray();
foreach (char c in Note) //check each character of Note
{
if (Newspaper.Contains(c))
{
Console.Write(c); //it will display hello
}
}
答案 2 :(得分:-1)
实际上,字符串是一个char数组。最经典的#34;这样做的方法是:
string Note = "hello";
char[] Newspaper = "ahrenlxlpoz".ToCharArray();
string res = "";
for (int i = 0; i < Note.Length; i++)
for (int j = 0; j < Newspaper.Length; j++)
if (Note[i] == Newspaper[j])
{
res += Newspaper[j];
Newspaper[j] = ' ';
break;
}
//This prints the remaining characters in Newspaper. I avoid repeating chars.
for (int i = 0; i < Newspaper.Length; i++ )
Console.Write(Newspaper[i]+"\n");
Console.Write("\n\n");
if (Note.Equals(res)) Console.Write("Word found");
else Console.Write("Word NOT found");
Console.Read();
最后,res将是&#34;你好&#34;。在控制台中打印res。我添加了' '
以避免重复的字符,就像有人在答案中说的那样。所以最后它会将结果与单词进行比较,并告诉你它是否在字符串中找到了单词。尝试将报纸更改为:"ahrenlxlpaz"
,它会告诉您找不到的单词:)