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.

Howard
  • 109
  • 2
  • 11

1 Answers1

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

Chuck
  • 1,977
  • 1
  • 17
  • 23
  • do you have any solution can out put the ans was `ans1 = "" ans2 = ""` and using for loop – Howard Apr 27 '22 at 15:37
  • 1
    @Howard: `var items = Regex.Matches(text, @"\<[^>]*\>").Cast().Select(m => m.Value).ToArray();` – Dmitry Bychenko Apr 27 '22 at 16:01
  • 1
    @Howard [Count how many `>` you have](https://stackoverflow.com/a/541994/5171120) 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](https://learn.microsoft.com/en-us/dotnet/api/system.string.remove?view=net-6.0) 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. – Chuck Apr 27 '22 at 16:01