目的:这个程序。从GirlNames.txt文件读取女孩名称,从BoyNames.txt文件读取男孩名称。此应用程序将这些名称放入单独的数组中,并且当用户输入男孩和/或女孩的名称时,该应用程序会显示一条消息,指出该名称是否是2000-2009年最受欢迎的名称之一。
private void searchButton_Click(object sender, EventArgs e)
{
try
{
//Opens BoyNames.txt & writes to list.
StreamReader boys;
string boyNames;
boys = File.OpenText("BoyNames.txt");
List<string> boyNameList = new List<string>();
//Opens GirlNames.txt & writes to list.
StreamReader girls;
string girlNames;
girls = File.OpenText("GirlNames.txt");
List<string> girlNameList = new List<string>();
// Get user input.
boyNames = boyNameTextBox.Text;
girlNames = girlNameTextBox.Text;
//Read Boys names
while (!boys.EndOfStream)
{
boyNameList.Add(boys.ReadLine());
} // end While loop.
//Read girls names
while (!girls.EndOfStream)
{
girlNameList.Add(girls.ReadLine());
} // end While loop.
int boysPosition = boyNameList.IndexOf(boyNames);
int girlsPosition = girlNameList.IndexOf(girlNames);
if (boysPosition != -1)
{
MessageBox.Show("The boy name you entered is one of the most popular names.");
} // end boys position IF loop.
if (girlsPosition != -1)
{
MessageBox.Show("The girl name you entered is one of the most popular names.");
} // end girlsPosition IF loop
if (boysPosition != -1 && girlsPosition != -1)
{
MessageBox.Show("The name you entered was found on both the boys and girls name lists!");
}
else if (boysPosition == -1)
{
MessageBox.Show("The boy name you have entered is NOT one of the most popular names.");
} // end Else If.
else if ( girlsPosition == -1)
{
MessageBox.Show("The girl name you have entered is NOT one of the most popular names.");
} // end Else If.
} // end try block.
catch (Exception ex)
{
// Display and error message.
MessageBox.Show(ex.Message);
} // end catch block.
} // end searchButton.
完全没有必要combinedList
。制作列表的额外副本只是浪费内存和CPU时间。
下面使用LINQ搜索两个列表:
string nameToSearch = "Some Name";
//if match is true, it exists in one of the lists
bool match = boyNameList.Any(x => x == nameToSearch) || girlNameList.Any(x => x == nameToSearch);
其他要考虑的事项是使用ReadAllLines
以及确切地如何定义两个字符串之间的匹配。上面的代码没有解决空白,文化,部分匹配等问题。
我将在此处找到的文档作为字符串比较的良好起点。乍一看,它所具有的不仅仅是眼神。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句