【问题标题】:Outputting a _ for each letter of a string in an array (hangman)为数组中字符串的每个字母输出一个 _ (hangman)
【发布时间】:2015-12-05 01:58:17
【问题描述】:
    public void Dashes()
    {
        for (int i = 0; i < SelectedWord.Length; i++)
            console.WriteLine("_");

    }

这是我唯一能想到的,每当我去运行它时,当我想要它放在 1 行时,它就会放在所有单独的行上

【问题讨论】:

  • 谢谢我所需要的一切。

标签: c# for-loop


【解决方案1】:
public void Dashes()
{
    for (int i = 0; i < SelectedWord.Length; i++)
        console.Write("_");

}

感谢@Grant Winney

【讨论】:

    【解决方案2】:

    试试这个

                string output = "";
                for (int i = 0; i < SelectedWord.Length; i++)
                {
                    output += "_";
                }
                console.WriteLine(output);
    

    【讨论】:

    • 为什么不简单地使用 Console.Write 而不是 Console.WriteLine 并保存所有不可变的连接?
    【解决方案3】:

    控制台,writeline 每次在循环中调用时都会打印一个新行。

    public void Dashes()
        {
            string dashes ="";
            for (int i = 0; i < SelectedWord.Length; i++)
                dashes +="_";
            console.WriteLine(dashes);
    
        }
    

    【讨论】:

    • 为什么不简单地使用 Console.Write 而不是 Console.WriteLine 并保存所有不可变的连接?
    • 你仍然需要一个 writeline()。问这个问题的人是新手,不要让事情变得过于复杂。
    【解决方案4】:

    如果运行 .NET 4 或更高版本,您也可以完全放弃循环并使用以下单行(根据 this answer):

    console.WriteLine(String.Concat(Enumerable.Repeat("_", SelectedWord.Length)));
    

    【讨论】:

      猜你喜欢
      • 2014-12-03
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 2019-11-04
      • 2015-12-29
      相关资源
      最近更新 更多