i am trying to make acronym using a title textbox on text change but i keep getting an error whenever i press space the error i get is
System.ArgumentOutOfRangeException: 'Index and length must refer to a location within the string. Parameter name: length'
this is what my form looks like: GUI
this is what my code looks like:
private void txtTitle_TextChanged(object sender, EventArgs e)
{
txtARC.Text = "";
if (!String.IsNullOrEmpty(txtTitle.Text))
{
string word = txtTitle.Text.ToString();
string[] wordArry = word.Split(' ');
for(int i=0; i<wordArry.Length; i++)
{
txtARC.Text = wordArry[i].Substring(0, 1);
}
}
}
If the text in the input box is "some words and a space "
,
then wordArry
will contain the strings "some", "words", "and", "a," "space", ""
. Note the empty string at the end! When you try to take the first character of an empty string, you get an exception.
You can do several things here.
You can instruct string.Split()
to ignore those empty strings:
string[] wordArry = word.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
You can check the bounds of the call to Substring
:
wordArry[i].Substring(0, Math.Min(1, wordArry[i].Length))
Or you can skip empty strings in the loop, like this
for (int i = 0; i < wordArry.Length; i++)
{
if(string.IsNullOrEmpty(wordArry[i])) {
continue;
}
// Process the string here
}