Howard
Howard

Reputation: 141

Have quesion while using C# string Substring method

Today I'm trying to fix some problem but i can't understand why return this Ans to me.

string text = "<Design><Code>"

var Ans = text.Substring(0, text.IndexOf(">"));

I can't understand why Ans will return "<Design" this to me. I think the "<Design>" <-- this Ans was correct.

Upvotes: 0

Views: 58

Answers (1)

Chuck
Chuck

Reputation: 2102

The problem is that IndexOf is going to return the zero-based index. text.Substring() is wanting the length as an argument, or the one-based number of characters in the string.

If I index, starting at zero, under your input:

<Design><Code>
01234567

You're passing 7 as the number of characters. If I count (starting at ONE) under your input:

<Design><Code>
1234567

You can see that the first seven characters are <Design

Upvotes: 4

Related Questions