Error when reassembling a string. Size is out

Asked

Viewed 839 times

0

I can’t fill out that list the way it is:

foreach (var item in text)
            {
                string[] linha = item.Split('\n');
                foreach (var i in linha)
                {
                    string nova_string = i.Substring(0, i.LastIndexOf("\r"));
                    lista.Add(nova_string);                    
                }                
            }

You’re making that mistake:

Length cannot be less than zero. Parameter name: length

1 answer

3


The expression i.LastIndexOf("\r") is not finding the character sought. When what is being searched within the string is not found the return of this method is -1, as documentation.

Then you can only use its output if you can ensure that the one you are looking for exists. You need to use a command if or the conditional operator ? : to decide what to do, or what result to return when the text does not exist.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.