Manto Manto - 1 month ago 7
C# Question

C# - Substring: index and length must refer to a location within the string

I have a string that looks like

string url = "";

"" is 18 fixed in length. I want to get the "aaa/bbb" part from this string (The actual url is not example nor aaa/bbb though, the length may vary)

so here's what I did:

string newString = url.Substring(18, url.Length - 4);

Then I got the exception: index and length must refer to a location within the string. What's wrong with my code and how to fix it? Thanks in advance.


The second parameter is the length of the substring, not the end index. This ought to work:

string newString = url.Substring(18, url.Length - 22); // 18 for part, and 4 for .jpg makes 22 to subtract from the length of the full URL to find the part we want

You should probably include handling to check that it does indeed start with what you expect, end with what you expect, and is at least as long as you expect. And then if it doesn't match, you can either do something else or throw a meaningful error.

Here's some example code that validates that url contains your strings, that also is refactored a bit to make it easier to change the prefix/suffix to strip:

var prefix = "";
var suffix = ".jpg";
string url = "";

if (url.StartsWith(prefix) && url.EndsWith(suffix) && url.Length >= (prefix.Length + suffix.Length))
    string newString = url.Substring(prefix.Length, url.Length - prefix.Length - suffix.Length);
    //handle invalid state