Lavi
Lavi

Reputation: 194

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

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?

Upvotes: 3

Views: 24241

Answers (4)

Vishalb
Vishalb

Reputation: 31

string[] exampleArray = str.Split(":");

Upvotes: 0

user798182
user798182

Reputation:

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]);
}

Upvotes: 8

Chaim Zonnenberg
Chaim Zonnenberg

Reputation: 1823

Simply use this:

foreach (string word in split) textBox1.Text = word.ToString(); 

Upvotes: 1

jtm001
jtm001

Reputation: 371

In response to " 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?"

var myWord = split[0...n]

Upvotes: 0

Related Questions