[英]Searching an Array using a while loop in C#?
我正在尝试使用while循环使用用户搜索输入来搜索数组,这是在我将一个单词电影标题列出到标准文本文件中的那一刻起,然后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[iOneWordTitle])
代替
if (sSearch == sOneWordTitle)
在您的版本中,您正在将字符串与字符串数组而不是数组索引值进行比较。
我可能还会考虑您的变量名。
它必须是这样的:
if (sSearch == sOneWordTitle[iOneWordTitle])
而不是在这里这样做:
if (sSearch == sOneWordTitle)
无需使用StreamReader
,您可以使用File.ReadAllLines()
轻松读取文本文件中的所有行。
您还在打印找不到 7次底片 。 如果您只希望打印一次,则可以保留一个bool
变量以指示未找到它。
您已将文件中的标题数量预先配置为7。如果文件中可以有更多标题,该怎么办?
因此,我认为您可能需要稍微更改代码:
int iOneWordTitle = 0;
string sSearch;
//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 all titles from the text file
string[] titles = File.ReadAllLines("filmnames.txt");
//Search the array
bool found = false;
foreach (string title in titles)
{
if (title.Equals(sSearch))
{
Console.WriteLine(sSearch + " was found");
found = true;
}
}
//If the title wasn't found, print not found message
if (!found)
Console.WriteLine("The film was not found");
如果仍然要打印找到它的位置,则可以将foreach
循环转换为常规循环:
for (int iOneWordTitle = 0; iOneWordTitle < titles.Count(); iOneWordTitle++)
{
if (titles[iOneWordTitle].Equals(sSearch))
{
Console.WriteLine(sSearch + " was found at position " + iOneWordTitle);
found = true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.