我試圖使用一個while循環來搜索一個數組,使用用戶搜索輸入,在我已經列出一個單詞電影標題到一個標準的文本文件,然後while循環不斷搜索文件,直到它找到,然後它在控制檯上輸出..但我有問題,運算符「==」不能應用於字符串變量?我將如何解決這個問題?非常感謝!聖誕快樂,這裏是我的代碼:在C#中使用while循環搜索數組?
//Declare variables
int iOneWordTitle= 0;
string sSearch;
//Declare array
const int iFilm = 7;
string[] sOneWordTitle = new string[iFilm];
//Add heading to console
Console.WriteLine("List of one word film titles");
Console.WriteLine();
//ask user what they want to search for
Console.WriteLine("What film would you like to search for?");
sSearch = Console.ReadLine();
//Read the film names from the datafile
using (StreamReader sr = new StreamReader("filmnames.txt"))
{
while (iOneWordTitle < iFilm)
{
sOneWordTitle[iOneWordTitle] = (sr.ReadLine());
iOneWordTitle++;
if (sSearch == sOneWordTitle)
{
Console.WriteLine(sSearch + " was found at position " + iOneWordTitle);
}
else
{
Console.WriteLine("The film was not found");
}
}
}
'if(sSearch == sOneWordTitle)'將字符串與字符串[]進行比較。你可能想弄清楚你真的想在那裏比較一下。 –
我希望如此,如果搜索等於電影,然後輸出它在控制檯上 – Tom
通過這樣做,你是比較字符串與數組對象,而不是數組中包含的字符串。 –