我需要检查数组的最终位置是否等于空格" &#34 ;.我的代码抛出一个超出范围的异常,而单词变量在末尾通过正则表达式模式包含一个空格。
代码:
string[] words = pattern.Split(input);
int limit = words.Count();
if(words[limit] == " ")
{ limit = limit - 1; }
答案 0 :(得分:2)
string[] words = pattern.Split(input);
int limit = words.Count();
if(words[limit-1] == " ")
{ limit = limit - 1; }
当使用count()时,数组位置需要为-1。感谢。
答案 1 :(得分:1)
.Count()
返回数组中元素的数量,但第一个元素索引为0,因此最后一个索引应为words.Count()-1
答案 2 :(得分:0)
您还可以使用以下代码。 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
}