Beast Mode
Beast Mode

Reputation: 27

Substring causing index and length error

I have a section in my code that I run to check to see if the item is an spanish item or english item. I am using this logic from an old vb.net application.

public int Spanish_Item()
{
    int i = 0;
    object j = 0;
    int k = 0;
    string ss = null;
    string sp_item = null;
    sp_item = TxtItem.Text.Trim();
    k = 0;
    for (i = 1; i <= 15; i++)
    {
        ss =  sp_item.Substring(i, 2);
        if (ss == "XX")
        {
            k = 1;
            i = 16;
        }
    }
    return k;
}

The following code loops around then I get this error message :

ex.Message "Index and length must refer to a location within the string.\r\nParameter name: length" string

please help!!!

Upvotes: 1

Views: 4637

Answers (2)

GMG
GMG

Reputation: 1618

In c# the first position is at index 0 not 1 like vb

public int Spanish_Item()
{
int i = 0;
object j = 0;
int k = 0;
string ss = null;
string sp_item = null;
sp_item = TxtItem.Text.Trim();
k = 0;
for (i = 0; i < sp_item.len-2; i++)
{
ss =  sp_item.Substring(i, 2);
if (ss == "XX")
{
k = 1;
i = 15;
}
}
return k;
}

you can use

if (sp_item.IndexOf("XX")>=0) {
    k=1;
}

Upvotes: 0

Lucero
Lucero

Reputation: 60190

You always go from 1 to 15 - if the (trimmed) text of TxtItem.Text is shorter then 15 chars you'll get the exception.

You should use the length-2 of sp_item as upper bound to avoid the error. Also, instead of setting i = 16 you should use break to stop the for loop.

However, I think your algorithm could also be written like this instead of the for loop:

if (sp_item.IndexOf("XX")>=1) {
    k=1;
}

Upvotes: 5

Related Questions