Fico
Fico

Reputation: 1

text files with string arrays get position substring

I am having a problem with the following:

I am loading a file into C# and then I am splitting it by lines with this code.

// Splitting by line from original file
string[] lines = showText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);

Now I need a for loop that will go through lines and get Substring from those lines, separately.

Here is what I am trying to accomplish, in a way:

for (int i = 0; i < lines.Length; i++)
{
    int[] testing = new int[i];
    testing[i] = int.Parse(lines[i].Substring(16, 1));
    textBox1.Text = testing.ToString();
}

The error here is: Index was outside the bounds of the array.

Here is a picture also to get better idea as to what I'm trying to do.

http://s30.postimg.org/jbmjmqv1t/work.jpg

textBox1.Text = lines[0].Substring(16,1) + "   " + lines[0].Substring(23,9);
textBox1.Text = lines[1].Substring(16,1) + "   " + lines[1].Substring(23,9); //etc

Could anyone help me with this?

Upvotes: 0

Views: 58

Answers (2)

Fico
Fico

Reputation: 1

This is how I've solved it.

int[] testing = new int[lines.Length];

textBox1.Clear(); //Just to clear it if button pressed again
for (int i = 0; i < lines.Length; i++)
{
    testing[i] = int.Parse(lines[i].Substring(16, 1));//just getting the needed value
    textBox1.Text += testing[i].ToString() + "\r\n" ;//adding each value to textBox1, separated by new line
}

Upvotes: 0

Serhat Ozgel
Serhat Ozgel

Reputation: 23796

You are creating the array in the for loop, so it is being created for each line and with the wrong length. Instead of this part of the code:

for (int i = 0; i < lines.Length; i++)
{
    int[] testing = new int[i];
    testing[i] = int.Parse(lines[i].Substring(16, 1));
    textBox1.Text = testing.ToString();
}

you should be doing this:

int[] testing = new int[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
    testing[i] = int.Parse(lines[i].Substring(16, 1));
    textBox1.Text = testing.ToString();
}

Upvotes: 2

Related Questions