当前位置: 动力学知识库 > 问答 > 编程问答 >

.net - substrings length

问题描述:

This is kind of a beginner's question but the code I am looking at is in production and I don't want to break anything. So, just in case: isn't

text.Substring(index, length).Length

is equivalent to just length?

(Except for the potential ArgumentOutOfRangeException.)

网友答案:

Yes, it will be exactly the same.

网友答案:

Looks like it to me. I can't see any reason for writing it like that.

网友答案:

Let's see what that actually means with some numbers:

"My groovy test string".Substring(0, 2).Length == "My".Length = 2

"My groovy test string".Substring(4, 2).Length == "ro" = 2

As you say, if startIndex + Length > length of the string, or startIndex isn't in the string then an ArgumentOutOfRangeException is thrown

So yes, as all of the potential other cases throw an exception.

My suspicion is the author didn't know that the edge case (when startIndex + length > end of string) throws an exception.

分享给朋友:
您可能感兴趣的文章:
随机阅读: