Hi all,
im trying to separate words in a string using whitespace " ".
but it gives ArgumentOutOfRangeExeception
: Index and length must refer to a location within the string.
Parameter name: length

it points to this line : if (textBox3.Text.Substring(i,c)==" ")

if (textBox3.Text != null)
            {
                ArrayList arrayKeyword = new ArrayList();
                int index = 0;
                
                int c = 0;
                for (int i = 0; i < textBox3.Text.Length;i++ )
                {
                  
                    c = i+1 ;
                  
                  
                    if (textBox3.Text.Substring(i,c)==" ")
                    {
                        string word = null;
                        word = textBox3.Text.Substring(0, i);
                        arrayKeyword[index]=word;
                        index = index + 1;
                    }
                }
               string pattern = null;
                for (int i = 0; i < arrayKeyword.Count; i++)
                {
                    pattern = "(\\w*"+arrayKeyword[i]+"\\w*)*";
                }
                MessageBox.Show(pattern);

PLZ help me.

for (int i = 0; i < textBox3.Text.Length;i++ )
{
 
c = i+1 ;
 
 
if (textBox3.Text.Substring(i,c)==" ")
{
string word = null;
word = textBox3.Text.Substring(0, i);
arrayKeyword[index]=word;
index = index + 1;
}
}

Your for-loop here iterates from the start of the string textBox3.Text to the end of the string. During each iteration, you check the current character (at position i) and the one following it (at position c). So when i is the last character in the string, c is invalid because there is no character following position i. You need to change your loop like so:

for (i = 0; i < textBox3.Text.Length - 1; i++)

EDIT: Actually, substring takes a start position and a length of the string, so your call to substring should be:

if (textBox3.Text.Substring(i,1)==" ")

Edited 5 Years Ago by darkagn: n/a

Comments
well explained.
for (int i = 0; i < textBox3.Text.Length;i++ )
{
 
c = i+1 ;
 
 
if (textBox3.Text.Substring(i,c)==" ")
{
string word = null;
word = textBox3.Text.Substring(0, i);
arrayKeyword[index]=word;
index = index + 1;
}
}

Your for-loop here iterates from the start of the string textBox3.Text to the end of the string. During each iteration, you check the current character (at position i) and the one following it (at position c). So when i is the last character in the string, c is invalid because there is no character following position i. You need to change your loop like so:

for (i = 0; i < textBox3.Text.Length - 1; i++)

EDIT: Actually, substring takes a start position and a length of the string, so your call to substring should be:

if (textBox3.Text.Substring(i,1)==" ")

thank you. it works.

This question has already been answered. Start a new discussion instead.