我试图借助字符串和重复指令解决的问题,但在控制台上结果不是我预期的

A problem that I tried to solve with the help of strings and repetitive instructions, but on the console the result is not what I expected

using System;

class Program
{
    static void Main(string[] args)
    {
        string candidateName = Console.ReadLine();
        string input = Console.ReadLine();

        int numberOfAdmittedPersons = Convert.ToInt32(input);

        string result = string.Empty;

        for (int i = 1; i <= numberOfAdmittedPersons; i++)
        {
            string listOfAllAdmittedPersons = Console.ReadLine();
            {
                if (i != numberOfAdmittedPersons)
                {
                   result += listOfAllAdmittedPersons;
                }
            }
        }

        if (result.Contains(candidateName))
        {
           Console.WriteLine("true");
        }
        else
        {
           Console.WriteLine("false");
        }
    }
}

应用程序在第一行收到候选人 C 的姓名(由用户输入)。下一行包含入场人数(也是用户输入)。然后是所有入场人数的列表,每行一个人(也是用户输入)。

我必须提交一份申请,如果候选人 C 被录取(C 在列表中找到),则显示“True”,如果候选人被拒绝(C 不在列表中),则显示“False” 例如:如果我输入:

John
3
George
Maria
John

控制台将显示:true

但我得到的结果是:false

我该怎么做才能更正我的代码?

您的代码有几个问题。导致您的错误的原因是这一行:

if (i != numberOfAdmittedPersons) 这意味着姓氏没有被添加到您的字符串中。

但是还有一个问题。给定以下输入:

MAX
2
AMA
XAVIER

结果将是 true,因为字符串 AMAXAVIER 包含字符串 MAX。答案是使用集合,例如:

string[] result = new string[numberOfAdmittedPersons];

for (int i = 0; i < numberOfAdmittedPersons; i++)
{
    result[i] = Console.ReadLine();
}

if (result.Contains(candidateName))
{
...

另一种方法是定义一个列表来存储名称。

List<string> result = new List<string>();

for (int i = 0; i < numberOfAdmittedPersons; i++)
{
    //  add items 
    result.Add(Console.ReadLine());
}

if (result.Contains(candidateName))
{
   // ...
}