0

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.

2
  • text.IndexOf(">") will return 7 here. so <Design is right - second argument to Substring() is number of characters to copy. Commented Apr 27, 2022 at 15:18
  • var Ans = text.Substring(0, text.IndexOf(">") + 1); Commented Apr 27, 2022 at 15:59

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

do you have any solution can out put the ans was ans1 = "<Design>" ans2 = "<Code>" and using for loop
@Howard: var items = Regex.Matches(text, @"\<[^>]*\>").Cast<Match>().Select(m => m.Value).ToArray();
@Howard Count how many > you have first, then you can do a for loop for each character you've got. The loop would get the index, get the substring, then remove the substring with text = text.Remove() and the same arguments you're passing to Substring(). I'd keep the ans as a List so you can .Add() answers dynamically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.