Search code examples
c#stringtextsplititerator

c# string iterator for showing words one by one


What I want to do is a program that includes textbox (or something else that allows me to do it ) and this textbox is going to show the text from my resource .txt file and this is going to be like one word after another or two words after another for users to improve eye-movement on the text. To make it more clear the textbox is going to show the words two by two . I can do it by using string array but it only works on Listbox and Listbox is not okay for this project because it goes vertical and I need horizontal text like as we see in books.

And this is the code that shows the logic of what ı want but ı cannot use it it stops when I click the button.

{
    public Form1()
    {
        InitializeComponent();
    }

    string[] kelimeler;


  

    private void button1_Click(object sender, EventArgs e)
    {
        const char Separator = ' ';
        kelimeler = Resource1.TextFile1.Split(Separator);

    }


    private void button2_Click(object sender, EventArgs e)
    {
        for (int i = 0; i< kelimeler.Length; i++)
        {
            textBox1.Text += kelimeler[i]+" " ;

            Thread.Sleep(200);


        }


        
    }
}

Solution

  • Here's how to do it with async and await. It uses async void, which is generally frowned upon, but it's the only way I know how to make a button handler async.

    I don't fish the starting string out of resources, I just do this:

    private const string Saying = @"Now is the time for all good men to come to the aid of the party";
    

    And, I carved of the retrieval and splitting of the string it's own function (that uses yield return to fabricate the enumerator).

    private IEnumerable<string> GetWords()
    {
        var words = Saying.Split(' ');
        foreach (var word in words)
        {
            yield return word;
        }
    }
    

    Then all that's left is the code that sticks the words in the text box. This code does what I think you want (puts the first word in the text box, pauses slightly, puts the next, pauses, etc.).

    private async void button3_Click(object sender, EventArgs e)
    {
        textBox4.Text = string.Empty;
        foreach (var word in GetWords())
        {
            textBox4.Text += (word + ' ');
            await Task.Delay(200);
        }
    }