从书中复制C#代码(假人为C#.0,无法获得预期的结果

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从书中复制C#代码(假人为C#.0,无法获得预期的结果相关的知识,希望对你有一定的参考价值。

预期结果是用户可以输入字符串,并且会构建一个句子,直到用户退出为止。将我的字符串加在一起时,字符串之间没有空格。

我曾尝试在句子后添加+ " ",但没有用。有任何想法吗?对不起,C#

public static void Main(string[] args)

    Console.WriteLine("Each line you enter will be  " + "added to a sentence until you " + 
    "enter EXIT  or QUIT");
    //Ask the user for input;  continue concatenating
    //the phrases input until the user enters exit or quit (start with an empty sentence).
    string sentence = "";
    for (; ; )
    
        //Get the next line.
        Console.WriteLine("Enter a string ");
        string line = Console.ReadLine();
        //Exit the loop if the  line  is a termiantor.
        string[] terms =  "EXIT", "exit", "QUIT", "quit" ;
        //compare the string  entered to each of the legal exit commands.
        bool quitting = false;
        foreach (string term in terms)
        
            //Break  out of the for loop if you  have a match.
            if (String.Compare(line, term) == 0)
            
                quitting = true;
            
        
        if (quitting == true)
        
            break;
        
        //Otherwise, add it to the sentence.
        sentence = String.Concat(sentence, line);
        //let the user know how she's doing.
        Console.WriteLine("\nyou've entered: " + sentence + " ");
    
    Console.WriteLine(" \ntotal sentence:\n " + sentence);

    //wait for user to acknowledge  results.
    Console.WriteLine("Press Enter to terminate...");
    Console.Read();



答案

尝试将空格添加为连接3个字符串的String.Concat重载方法的一部分

sentence = String.Concat(sentence, " ", line);
另一答案

C#中的字符串是不可变的,这意味着您每次更改字符串都会得到一个新的副本。

[执行时:

Console.WriteLine("\nyou've entered: " + sentence + " ");

您正在创建将传递给Console.WriteLine的字符串,但没有更改原始sentence变量。

当您使用sentence合并新字符串时,您可以简单地添加空格:

sentence = String.Concat(sentence, line, " ");
另一答案

String.Concat(sentence, " " + line);

以上是关于从书中复制C#代码(假人为C#.0,无法获得预期的结果的主要内容,如果未能解决你的问题,请参考以下文章

C语言中有范围解析运算符吗?

我正在尝试用 C 构建一个示例 gtk+

C ++中单独文件中的类?

如何在 Java 中成功地从书中删除标签?

使用 control.step_response 无法获得预期的输出

如何从 Kindle PC 复制代码并保留格式