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

后端 未结 8 1335
有刺的猬
有刺的猬 2020-12-05 23:31

I have a string that looks like

string url = \"www.example.com/aaa/bbb.jpg\";

\"www.example.com/\" is 18 fixed in length. I want to get th

相关标签:
8条回答
  • 2020-12-06 00:03

    You need to check your statement like this :

    string url = "www.example.com/aaa/bbb.jpg";
    string lenght = url.Lenght-4;
    if(url.Lenght > 15)//eg 15
    {
     string newString = url.Substring(18, lenght);
    }
    
    0 讨论(0)
  • 2020-12-06 00:09

    The second parameter in Substring is the length of the substring, not the end index.

    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 = "www.example.com/";
    var suffix = ".jpg";
    string url = "www.example.com/aaa/bbb.jpg";
    
    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);
        Console.WriteLine(newString);
    }
    else
        //handle invalid state
    
    0 讨论(0)
提交回复
热议问题