Richard77
Richard77

Reputation: 21621

index and length must refer to a location within the string. parameter name length

I'm looking for a match in a string. If there is one, I take the sub-string before the first occurrence and the sub-string after the match.

Unfortunately, the second part of the process is throwing an exception. "index and length must refer to a location within the string. parameter name length"

string str1 = (firstIndex > 0) 
          ? line.Substring(0, firstIndex) : string.Empty;


string str3 = (lastIdx < line.Length - 1) 
    ? line.Substring(lastIdx + 1, line.Length - 1) : string.Empty;// This line
                                                                  //is causing problem

Thanks for helping.

Upvotes: 0

Views: 2229

Answers (3)

DavidRR
DavidRR

Reputation: 19397

From MSDN, String.Substring Method (Int32):

Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.

This example shows the use of both the one- and two-argument versions of String.Substring():

using System;

public class Test
{
    public static void Main()
    {
        var line = "stackoverflow";
        //               ^  ^
        //               a  b

        var firstIndex = 5;  // a
        var lastIndex = 8;   // b

        // Extracts "stack".
        string str1 = (firstIndex > 0)
            ? line.Substring(0, firstIndex) : string.Empty;

        // Extracts "flow".
        string str3 = (lastIndex < line.Length - 1)
            ? line.Substring(lastIndex + 1) : string.Empty;

        Console.WriteLine("first: [{0}]\nlast[{1}]\n", str1, str3);
    }
}

Upvotes: 0

AlexD
AlexD

Reputation: 32576

When you take substring, you need to specify the length of the substring, not the index of the last character.

Instead of

line.Substring(lastIdx + 1, line.Length - 1)

try

line.Substring(lastIdx + 1, line.Length - (lastIdx + 1))

(or just omit the second parameter as @Selman22 suggested.)

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Second parameter of Substring is length. If you want to get substring starting from lastIdx + 1 to the end of your string then just don't pass a lenght parameter. Use:

string str3 = (lastIdx < line.Length - 1) 
   ? line.Substring(lastIdx + 1) : string.Empty;

Upvotes: 2

Related Questions