Копирование кода C # из книги (C # .0 для чайников) не может дать ожидаемый результат - PullRequest
1 голос
/ 26 октября 2019

Ожидаемый результат заключается в том, что пользователь может вводить строку, и он строит предложение, пока пользователь не завершит работу. Когда мои строки складываются вместе, между строками нет места.

Я попытался добавить + " " после предложения, и это не сработало. есть идеи? извините, новичок в 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 ]

1 голос
/ 26 октября 2019

Попробуйте добавить пробел как часть перегруженных методов String.Concat, объединяющих 3 строки

sentence = String.Concat(sentence, " ", line);
0 голосов
/ 26 октября 2019

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

0 голосов
/ 26 октября 2019

Строки в C # являются неизменяемыми, то есть вы получаете новую копию строки каждый раз, когда вы ее изменяете.

Когда вы делаете:

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

Вы создаете строку, котораябудет передан в Console.WriteLine, но без изменения вашей исходной переменной sentence.

Вы можете просто добавить пробел при конкататации новой строки с помощью sentence:

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