Место общения программистов C#
-
Anonymous
Как получить n-е слово из строки, если между словами больше пробелов?
Сообщение
Anonymous »
Я пытаюсь распечатать x-е слово из такого предложения:
Код: Выделить всё
string phrase = Console.ReadLine();
int wordIndex = Convert.ToInt32(Console.ReadLine());
string currentWord = "";
int currentWordIndex = 1;
for (int i = 0; i < phrase.Length; i++)
{
if (phrase[i] != ' ')
currentWord += phrase[i];
if (phrase[i] == ' ' || i == phrase.Length - 1)
{
if (wordIndex == currentWordIndex)
{
Console.WriteLine(currentWord);
break;
}
currentWord = "";
if (i != phrase.Length - 1)
currentWordIndex++;
}
}
if (wordIndex > currentWordIndex)
Console.WriteLine("N/A");
Я хочу, чтобы это работало, даже если между словами больше пробелов. Помогите, пожалуйста?
Подробнее здесь:
https://stackoverflow.com/questions/526 ... -the-words
1760181120
Anonymous
Я пытаюсь распечатать x-е слово из такого предложения:
[code]string phrase = Console.ReadLine();
int wordIndex = Convert.ToInt32(Console.ReadLine());
string currentWord = "";
int currentWordIndex = 1;
for (int i = 0; i < phrase.Length; i++)
{
if (phrase[i] != ' ')
currentWord += phrase[i];
if (phrase[i] == ' ' || i == phrase.Length - 1)
{
if (wordIndex == currentWordIndex)
{
Console.WriteLine(currentWord);
break;
}
currentWord = "";
if (i != phrase.Length - 1)
currentWordIndex++;
}
}
if (wordIndex > currentWordIndex)
Console.WriteLine("N/A");
[/code]
Я хочу, чтобы это работало, даже если между словами больше пробелов. Помогите, пожалуйста?
Подробнее здесь: [url]https://stackoverflow.com/questions/52662958/how-to-get-the-nth-word-from-a-string-if-there-are-more-spaces-between-the-words[/url]