Search code examples
c#arraysstringwinformsint

Read string array with an int selector C#


I have the following code to create a string array named "Lines" from pasted code and add an item for every array from the "Lines" string into a listBox.

string Temp = Clipboard.GetText();
int count = 1;
for (int i = 0; i < Temp.Length; i++)
{
    if (Temp[i] == '\n') count++;
}
string[] lines = Temp.Split(
new[] { Environment.NewLine },
StringSplitOptions.None
);
int reader = 1;
int repeat = count;
for (int i = 0; i < repeat; i++)
{
    ListBox.Items.Add(lines[reader]);
    reader = reader + 1;
}

When this code is used in Visual Studio, everything seems fine,

but when I run this code I receive the following error :

System.IndexOutOfRangeException ;

which means that the array index is out of reach. When I replace

ListBox.Items.Add(lines[reader]); 

with

ListBox.Items.Add(lines[1]); 

for example, it works fine. This means the issue comes from the "reader" int but I can't seem to find a way to fix it.

How could I fix this?


Solution

  • The problem is likely that you're starting your counter variables at 1, then using that as an index into the array, but array's are zero-based in c# so you're essentially skipping the first item at 0 and then trying to access an item that's out of the bounds of the array.

    It's also not accurate to count the \n characters and expect that to be equal to the number of Environment.NewLine instances.

    It also seems you have a lot of unnecessary variables to track counting. Instead, your code could be reduced to:

    string temp = Clipboard.GetText();
            
    string[] lines = temp.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
    
    for (int i = 0; i < lines.Length; i++)
    {
        ListBox.Items.Add(lines[i]);
    }
    

    Or, you could just do it all in one line:

    ListBox.Items.AddRange(
        Clipboard.GetText().Split(new[] {Environment.NewLine}, StringSplitOptions.None));