【问题标题】:How do I add +string within a text?如何在文本中添加 +string?
【发布时间】:2017-11-21 15:29:39
【问题描述】:

我想知道如何在 Console.WriteLine / Console.Write 中添加 [+line]。

例如:

string line;
    Console.WriteLine("Enter one or more lines of text (press 'gg' to exit):");
    do
    {
       Console.Write(" ");
        line = Console.ReadLine();
        if (line != "b")
            Console.WriteLine(" Sorry, you wrote **???**, which is wrong. \n Try again." +line);
       else
           Console.WriteLine("u rock");
    }
           while ( line != "gg") ;

我想在句子中间添加 [+line],也就是问号所在的位置。 我该怎么做?

【问题讨论】:

    标签: string readline console.writeline


    【解决方案1】:

    String interpolation 是您最好的选择(假设您使用的是 C# 6 或更高版本)。记住字符串开头的 $:

    Console.WriteLine($"Sorry, you wrote {line}, which is wrong. \n Try again.");
    

    你也可以用来分开添加在一起的字符串,虽然这有点笨拙:

    Console.WriteLine("Sorry, you wrote " +  line + ", which is wrong. \n Try again.");
    

    【讨论】:

    • 非常感谢!我尝试写{+line},但不知道它没有+,我不得不在开始时使用$。非常感谢!不过,我必须再等 10 分钟才能批准答案...
    • 您能否从给定的代码中告诉我,如何在不添加新行的情况下从控制台读取输入的文本?我的意思是,我写了一个词,然后按 Enter 后,它会直接强制 Console.WriteLine 而不在控制台中注册我写了哪些字符?
    • 你的意思是你不希望你输入的字符出现,就像你输入密码一样?
    • Picture here 当我写它们时它们会出现,但我不希望在按 Enter 时被记录在新的原始文件中。我想在按 Enter 后直接收到 Console.WriteLine 消息。
    猜你喜欢
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    相关资源
    最近更新 更多