I need to check if the final place of an array is equal to a space " ". My code below throws an out of range exception and the words variable includes a space at the end through a regex pattern.
Code:
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; }
The array position needs to be -1 when a count() is used. Thanks.
.Count()
返回数组中元素的数量,但第一个元素索引为0,因此最后一个索引应为words.Count()-1
You can also use the following code. The IsNullOrWhiteSpace
method checks if a given string only consists null or white space characters.
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.