T
T
Tony13372017-04-27 03:43:47
JavaScript
Tony1337, 2017-04-27 03:43:47

C# - How to assign a variable to a specific place in a sentence?

Hello. I wrote one program, and for some function it was necessary to make such a function that when you enter (ReadLine) the words "create a notebook" - which notebook to create (the third word) becomes the variable a. Now I need to make it possible to declare the second word of a variable (create ... notepad) or two words in the middle (create ... ... notepad). How can this be implemented? I would be glad to help. Here is the code:

string line = Console.ReadLine();
if (line.Substring(0, 15).ToLower() == "создать блокнот")
{
string a = line.Substring(7);
while (a.Substring(0, 1) == " ")
{
a = a.Substring(9);
}
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dymok, 2018-05-26
@Nichosi

https://codepen.io/anon/pen/RyXKpE

D
Daniel Demidko, 2017-04-27
@Tony1337

The following instruction will split the read string into an array of words, regardless of the number of spaces between them, and assign it to the wordsArray variable. You can also specify any of your characters for splitting.

String[] wordsArray = 
Console
     // Считываем строку
    .ReadLine()
     // Разбиваем её
    .Split(
     //Массив разделительных символов, вызов .ToArray необходим
             " ".ToArray(),
    // Указание пропускать повторы разделительных символов
             StringSplitOptions.RemoveEmptyEntries )

V
vvovas, 2017-04-27
@vvovas

line.Split(' ') - will split your string into words and return an array of words. Then work with him.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question