C# - Substring:索引和长度必须指向字符串中的一个位置 [英] C# - Substring: index and length must refer to a location within the string

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

问题描述

我有一个字符串,看起来像

I have a string that looks like

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

www.example.com/的长度是18。我想从这个字符串中获取aaa / bbb部分(实际的url不是例子,也不是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)

所以这里是什么我做了:

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.

推荐答案

Substring 是子串的长度,而不是结束索引

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包含你的字符串的示例代码,也是被重构了一点,以便将前缀/后缀更改为strip:

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

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

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