vendredi 5 octobre 2018

How to get the nth word from a string if there are more spaces between the words?

I am trying to print out the xth word from a sentence like this:

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");

I want it to work even if there are more spaces between words. Any help, please?

Aucun commentaire:

Enregistrer un commentaire