rahularyansharma
rahularyansharma

Reputation: 10755

Index and length must refer to a location within the string

I have some address like this

122/852 Mansrovar society,Jaipur, Rajastha,India

where i need to write a function which extract Mansrovar society I tried below code but giving me error

 string BuildingAddress = txtAddress.Substring(0, txtAddress.IndexOf(','));
            BuildingAddress = BuildingAddress.Substring(BuildingAddress.IndexOf(' '), BuildingAddress.Length);

Upvotes: 0

Views: 89

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500515

The second argument of string.Substring(int, int) is the length of the substring you want - so

BuildingAddress = BuildingAddress.Substring(BuildingAddress.IndexOf(' '),
                                            BuildingAddress.Length);

would only be valid if IndexOf returned 0.

If you just want "from the first space onwards" you can use the overload with a single parameter:

BuildingAddress = BuildingAddress.Substring(BuildingAddress.IndexOf(' '));

Note that that will still fail if the string doesn't contain a space - and it will have a leading space if it works. You might want:

BuildingAddress = BuildingAddress.Substring(BuildingAddress.IndexOf(' ') + 1);

which will always be valid, and skip the leading space - although it will only skip one space.

Upvotes: 4

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

String.Substring takes two arguments: start and length. You're using it as if the second one was end. It's not.

BuildingAddress =
    BuildingAddress.Substring(BuildingAddress.IndexOf(' '),
                              BuildingAddress.Length - BuildingAddress.IndexOf(' '));

Upvotes: 2

Related Questions