I am unsure why this is throwing an exception. This code is supposed to take the cursor position then get the last index of space or enter to pick out a the last single word typed.It sometimes throws an exception of out of range. Is the selection start value going to be higher than number of characters in the string? I am unsure what exactly is causing this. I put the if statement to avoid doing an index of characters that dont exist ... but that didn't improve or worsen it one way or the other.
private string word()
{
char[] array1 = { '\n', ' ' };
int end = textBox1.SelectionStart;
int strt = 0;
if (textBox1.Text.LastIndexOfAny(array1)!=-1)
{
strt = textBox1.Text.LastIndexOfAny(array1,end);
}
if (strt==-1) { strt = 0; }
return textBox1.Text.Substring(strt, end - strt);
}
As per MSDN,
String.LastIndexOfAny Method (Char[], Int32)
Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array. The search starts at a specified character position and proceeds backward toward the beginning of the string.
In your case the textBox1.SelectionStart
will give you the current position of the cursor in the Textbox. Let the string in the TextBox be "sampl"
and the cursor is at end of the text, so the SelectionStart will give you the value 5
. Please note that the string in the box is of length 5
but it doesn't have a character at index 5
since it follows 0
based indexing.
Hence while accessing this code strt = textBox1.Text.LastIndexOfAny(array1,end);
the 5
is not a valid index in the string. that causes the error here.
So use the following lines to get the cursor position(end
), then your code will works as you expected
int end = 0;
if (textBox1.Text.Length > 1)
end = textBox1.SelectionStart - 1;