Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(C#) - store each word between Split in an array

Tags:

arrays

c#

split

lets say that was the text in the file. it would remove the colons, and put each word into it's own string in an array. for example:

exampleArray[0] = 'hello' 
exampleArray[1] = 'my'
exampleArray[2] = 'name'
exampleArray[3] = 'is'
exampleArray[4] = 'lavi'

This is my code:

private void button2_Click(object sender, EventArgs e)
    {
        listBox1.Items.Clear();
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = "Text Files|*.txt";
        DialogResult result = ofd.ShowDialog();

        if(result == DialogResult.OK)
        {
            StreamReader textfile = new StreamReader(ofd.FileName); 

            string s = textfile.ReadToEnd();

            string[] split = s.Split(':', '\n');

            foreach (string word in split)
                textBox1.Text = word[0].ToString();
                //listBox1.Items.Add(word);


            ofd.Dispose();
        }

thanks!

edit: What I meant to say is how do I make it so each word is stored in an array so I can access it later with [0], [1], [2], etc.? If Split does that automatically, how do I access each word?

like image 279
Lavi Avatar asked May 14 '26 01:05

Lavi


1 Answers

It does it automatically (String.split, that is)

String str = "hello:my:name:is:lavi";
var words = str.Split(":");
Console.WriteLine(words[1]); //This prints out 'my';
for (int i=0;i<words.Length;i++) {  //This will print out each word on a separate line
    Console.WriteLine(words[i]);
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!