子字符串的索引和长度必须引用字符串中的位置 [英] Substring index and length must refer to a location within the string

查看:69
本文介绍了子字符串的索引和长度必须引用字符串中的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像

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

这篇关于子字符串的索引和长度必须引用字符串中的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆