Home > Net >  How to write a word from a string. c#
How to write a word from a string. c#

Time:06-06

I've started recently to learn c# and I have a problem. The problem gives me a sentence and a number and my program has to return that number's word. Here is what I've made:

using System;

string inputData = Console.ReadLine();
string text = inputData;
inputData=Console.ReadLine();
int x = Convert.ToInt32(inputData);
string currentWord = String.Empty;
int wordCount = 1;
for (int i = 0; i < text.Length;   i)
{
    if (text[i] == ' ')
    {
        wordCount  ; currentWord = String.Empty;
        while (text[i] == ' ') i  ;
    }
    if (text[i] != ' ') { currentWord  = text[i]; }
    if (wordCount == x) Console.WriteLine(currentWord);
}
Console.Read();

For the sentence " I have two pens" and the number 2, the program returns h ha hav have. What do I do wrong?

CodePudding user response:

I would change it a bit. The problem why it's is giving multiple values, is because you don't terminate the iteration. (break the forloop). I've added some comment to it:

class Program
{
    static void Main(string[] args)
    {
        // some test data (instead of readline)
        string inputData = " I have two pens";
        string text = inputData;
        inputData = "2";
        int x = Convert.ToInt32(inputData);
        
        string currentWord = String.Empty;
        int wordCount = 1;

        // To fix te last word, just add a space, so we always end with a space.
        inputData  = " ";

        for (int i = 0; i < text.Length; i  )
        {
            // when the character is a space and the currentWord has something
            // a new word has been found.
            if (text[i] == ' ' && !string.IsNullOrEmpty(currentWord))
            {
                // when a new word has been found, just check it.
                if (wordCount == x)
                {
                    Console.WriteLine(currentWord);
                    // this is where your solution fails.
                    // when the word has been found, break the iteration.
                    break;
                }

                wordCount  ;
                currentWord = String.Empty;
            }
            else if (text[i] != ' ')
            {
                currentWord  = text[i];
            }
        }

        Console.Read();
    }
}

You could use System.Linq for this, which is much easier.

// Split the string on space and create an array.
// Skip some elements and select the first.
var s = text.Split(' ').Skip(x).FirstOrDefault();
Console.WriteLine(s);
  • Related