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?
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. Ifstartis 2 and the length of the string is 11, thenendwould be 10.. which if added together makes 12 (10+2=12.. while the length of the string is 11).You need this:
..and this: