0

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

3 Answers 3

2
    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.

Sign up to request clarification or add additional context in comments.

Comments

1

.Count() returns the number of elements in your array, but the first elements index is 0, so the last index should be words.Count()-1

2 Comments

The final element will equal to 'limit' in this case. How do it write an if-statement if final element == (" ") ?
Thanks for that. I totally spaced out on that one. Cheers.
0

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
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.