检查阵列位置是空的还是空间

  • 本文关键字:空间 阵列 位置 c#
  • 更新时间 :
  • 英文 :


我需要检查数组的最后位置是否等于空间"。我下面的代码抛出了一个超出范围的异常,单词变量在末端通过正则模式包含一个空间。

代码:

string[] words = pattern.Split(input);
int limit = words.Count();
if(words[limit] == " ")
{ limit = limit - 1;  }
    string[] words = pattern.Split(input);
    int limit = words.Count();
    if(words[limit-1] == " ")
    { limit = limit - 1;  }

使用计数()时,数组位置需要为-1。谢谢。

.Count()返回数组中的元素数,但第一个元素索引为0,因此最后一个索引应为 words.Count()-1

您还可以使用以下代码。IsNullOrWhiteSpace方法检查给定的字符串是否仅组成空空间字符。

    string[] words = pattern.Split(input);
    int limit = words.Length;
    if(String.IsNullOrWhiteSpace(words[limit-1]))
    {
      limit-=1; //edit value of limit based on your own logic
    }

最新更新