這是我必須處理的練習:
給你一個單詞和一個單詞串列。你的任務是檢查串列中的所有單詞是否都是單詞的字謎。輸入 從標準輸入讀取
在第一行,找到 W - 要檢查的單詞;在第二行,找到 N - 單詞串列 WORDS 中的單詞數;在接下來的 N 行中,來自 WORDS 的單詞;輸出 列印到標準輸出
對于 WORDS 中的每個單詞,列印:“是”,如果該單詞是 W 的字謎;“不”,如果這個詞不是 W 的字謎;
這是我的代碼:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string word1 = Console.ReadLine();
char[] mainWord = word1.ToLower().ToCharArray();
Array.Sort(mainWord);
int numberOfWords = int.Parse(Console.ReadLine());
List<Array> anagramWords = new List<Array>();
for (int i = 0; i < numberOfWords; i )
{
string wordForList = Console.ReadLine();
char[] wordCharacters = wordForList.ToLower().ToCharArray();
Array.Sort(wordCharacters);
anagramWords.Add(wordCharacters);
}
foreach(object word in anagramWords)
{
if (word == mainWord)
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
}
出于某種原因,我得到的答案始終是否定的。
uj5u.com熱心網友回復:
if (word == mainWord)
不將單詞陣列的內容與mainWord陣列的內容進行比較。
陣列變數是參考型別,換句話說,它們只包含對真正存盤陣列元素的記憶體區域的參考。
因此,如果您以這種方式比較兩個陣列,您就是在比較指向存盤相應元素的記憶體區域的兩個值(兩個參考)。當然這些值是不同的,因為即使陣列包含相同的字符,元素也存盤在不同的記憶體區域。
要解決您的問題,需要采用不同的方法。
這樣的事情應該作業
static void Main()
{
string word1 = Console.ReadLine();
IEnumerable<char>mainWord = word1.ToLower().OrderBy(w => w);
int numberOfWords = int.Parse(Console.ReadLine());
List<IEnumerable<char>> anagramWords = new List<IEnumerable<char>>();
for (int i = 0; i < numberOfWords; i )
{
string wordForList = Console.ReadLine();
IEnumerable<char> wordCharacters = wordForList.ToLower().OrderBy(fl => fl);
anagramWords.Add(wordCharacters);
}
foreach (var word in anagramWords)
{
// Here we are asking to compare the full set of elements
// with each other and we find if they contain the same data.
if (word.SequenceEqual(mainWord))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385966.html
標籤:C#
