【问题标题】:Creating Acronym on text change c# [duplicate]在文本更改c#上创建首字母缩写词[重复]
【发布时间】:2021-02-01 20:30:01
【问题描述】:

我正在尝试在文本更改时使用标题文本框来制作首字母缩写词 但是每当我按空格键时,我都会收到错误消息 我得到的错误是

System.ArgumentOutOfRangeException: '索引和长度必须引用一个 字符串中的位置。参数名称:长度'

  • 这是我的表单的样子: GUI

  • 这是我的代码的样子:

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

【问题讨论】:

  • 听起来您正试图从零字符的字符串中获取第一个字符。发生这种情况时,wordArry[i] 的运行时值是多少?你期望它是什么?为什么? word 的值是多少?你期望它是什么?为什么?在最简单的情况下,您无法从空字符串中获取第一个字符,因为它没有字符。在尝试获取子字符串之前,您可能只检查字符串的长度。

标签: c# winforms textchanged


【解决方案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  
} 

【讨论】:

    【解决方案2】:

    让我们提取方法 - 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);
      }
    

    【讨论】:

    • 感谢您的回答,这也是一个很好的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多