子字符串的索引和长度必须引用字符串中的位置

问题描述:

我有一个看起来像

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

"www.example.com/"的长度固定为18.我想从该字符串中获取"aaa/bbb"部分(尽管实际网址不是示例,也不是aaa/bbb,但长度可能会有所不同)

"www.example.com/" 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)

这就是我所做的:

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 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.

下面是一些示例代码,用于验证url是否包含您的字符串,还对其进行了重构,以使其更容易更改前缀/后缀以剥离:

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