在文本更改时创建首字母缩略词 c#

Creating Acronym on text change c#

我正在尝试在文本更改时使用标题文本框制作首字母缩略词 但是每当我按 space 时,我总是收到错误消息 我得到的错误是

System.ArgumentOutOfRangeException: 'Index and length must refer to a location within the string. Parameter name: length'

    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);
                }
            }
        }

如果输入框中的文字是"some words and a space ", 那么 wordArry 将包含字符串 "some", "words", "and", "a," "space", ""。注意末尾的空字符串!当您尝试获取空字符串的第一个字符时,您会遇到异常。

您可以在这里做几件事。

您可以指示 string.Split() 忽略那些空字符串:

string[] wordArry = word.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

您可以检查对 Substring:

的调用范围
wordArry[i].Substring(0, Math.Min(1, wordArry[i].Length))

或者你可以跳过循环中的空字符串,像这样

for (int i = 0; i < wordArry.Length; i++)
{
    if(string.IsNullOrEmpty(wordArry[i])) {
        continue;
    }

    // Process the string here  
} 

让我们提取方法 - ToAcronym;我们可以使用正则表达式来实现它:我们可以Match所有的单词(我们定义为非空字母序列)并从每个单词中取出第一个字符:

代码:

  using System.Linq;
  using System.Text.RegularExpressions;

  ...

  public static string ToAcronym(string value) {
    if (string.IsNullOrWhiteSpace(value))
      return "";

    return string.Concat(Regex
      .Matches(value, @"\p{L}+")
      .Cast<Match>()
      .Select(match => match.Value[0]));
  }

演示:

  string[] tests = new string[] {
    "Quick Brown Fox",
    "word",
    "Два Слова", // "Two Words" in Russian
    "Have (Some) Punctuation!"
  };

  string report = string.Join(Environment.NewLine, tests
    .Select(test => $"{test,-25} => {ToAcronym(test)}"));

  Console.Write(report);

结果:

Quick Brown Fox           => QBF
word                      => w
Два Слова                 => ДС
Have (Some) Punctuation!  => HSP

您的代码可以

  private void txtTitle_TextChanged(object sender, EventArgs e) {
    txtARC.Text = ToAcronym(txtTitle.Text);
  }