有什么方法可以将char Array保存在For循环中?

时间:2018-09-10 15:47:14

标签: c#

我想创建一个简单的子手,并且陷入了:/。 这是检测数组中所有字符的简单代码。 我需要某种方式保存并编写它。 我在代码中添加了注释,以提高可读性和保存位置。 最后,我需要编写它。 有什么我可以做得更好的代码吗?我是新手。

public static void Main(string[] args)
{
    char[] array;
    randomWord = "apple".ToCharArray();
    Console.WriteLine(randomWord);
    while (guessing == true) {


    Console.WriteLine();


    userinput = char.Parse(Console.ReadLine());

    for (int i = 0; i < randomWord.Length; i++)
    {
        if (randomWord[i].ToString().Contains(userinput))
        {

        Console.Write(userinput);
        //add to array
         enter code here

        }
        else
        {
        //add to array
         enter code here
        Console.Write("_ ");
        }
    }
    //and here Write whole array
    for(int g = 0; g < array.Lenght; g++){
       Console.Write(array[g]);
    }
}

1 个答案:

答案 0 :(得分:0)

使用generic list (List<T>),它们比数组更灵活:

public static void Main(string[] args)
{
    List<char> array = new List<char>();
    randomWord = "apple".ToCharArray();
    Console.WriteLine(randomWord);
    while (guessing == true) {


        Console.WriteLine();


        userinput = char.Parse(Console.ReadLine());

        for (int i = 0; i < randomWord.Length; i++)
        {
            if (randomWord[i].ToString().Contains(userinput))
            {

               Console.Write(userinput);
               //add to array
                array.Add(randomWord[i]);

            }
            else
            {
               //it's not clear what you want to add to here?
               Console.Write("_ ");
            }
        }
        //and here Write whole array
        //use a foreach
        foreach(char c in array ){
           Console.Write(c);
        }
    //your missing a brace
    }
}
相关问题