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

问题描述 投票:2回答:3

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

我曾尝试在句子后添加+ " ",但没有用。有任何想法吗?对不起,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();
}


c# string concat
3个回答
0
投票

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

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

0
投票

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

[执行时:

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

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

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

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.