ThreadRoar
ThreadRoar

Reputation: 241

Why is string.Length not working on text.Substring?

I'm trying to get the string after the given word. Below is the code.

private static string GetStringAfterWord(string text, int position)
    {
        if (text.Length - 1 < position || text[position] == ' ') return null;

        int start = position;
        int end = position;

        while (end < text.Length - 1 )   
        end++;

        return text.Substring(start, end);

    }

This code always give me this error: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.

Isn't the string.Length return the number of total characters and why is always out of range. Am i doing this wrong?

Upvotes: 0

Views: 1902

Answers (3)

Michael Tsai
Michael Tsai

Reputation: 711

The 2nd argument of Substring() method is not an index, it's a length.

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65049

string.SubString's second argument is the length of the substring.

In your example, you're saying grab the string starting at <start> and is <end> characters long. If start is 2 and the length of the string is 11, then end would be 10.. which if added together makes 12 (10+2=12.. while the length of the string is 11).

You need this:

return text.Substring(start, end - start);

..and this:

while (end < text.Length)

Upvotes: 1

Sidharth Mudgal
Sidharth Mudgal

Reputation: 4264

It should be:

if (text.Length - 1 < position || position < 0 || text[position] == ' ')

And replace

 while (end < text.Length - 1 )   
    end++;

with

 end = text.Length - start;

Upvotes: 1

Related Questions