1

I have the following string.

"<This is my string=NHUYT>"

I would like to get words between "=" and ">" but I would like to make this generic, not for only this word NHUYT.

Using substring I tried:

var line = "<This is my string=NHUYT>"
var index = line.Trim().IndexOf("=");
var lastIndex = line.Trim().IndexOf(">");

var id = line.Substring(index, lastIndex);

But I can't do that because lastIndex is actually the length, so how can I do this?

Substring(Int32, Int32) Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

Kevin Ghadyani
  • 6,829
  • 6
  • 44
  • 62
Leonardo Lima
  • 586
  • 1
  • 6
  • 20
  • `but I would to make this generic, not for only this word NHUYT.` what actually do you mean by **generic** ? – er-sho Feb 25 '19 at 13:42
  • 4
    `lastIndex - index`? – UnholySheep Feb 25 '19 at 13:42
  • 1
    You shouldn´t provide the last **index**, but the **length**, which is `lastIndex - firstIndex`. – MakePeaceGreatAgain Feb 25 '19 at 13:42
  • 1
    ... although I think you mean `(index + 1, lastIndex - (index + 1))`, else you'll get "=NHUYT". And for consistency you should Trim before Substringing, and / or just trim line in the first place. – Rup Feb 25 '19 at 13:43
  • You you describe more what strings may appear? It would be good to better understand the rules of them. Example: Could there be something like "" With another equal in it? – Malior Feb 25 '19 at 13:44
  • @er-sho for other word, for example string=BSCHTEGRTH – Leonardo Lima Feb 25 '19 at 13:44

1 Answers1

3

You can get the length by subtracting the first index from the last index. Also if you are going to Trim(), do it once in the initial string rather than when finding the IndexOf, because when you're doing the substring you're not trimming and the indexes might be off.

var line = "<This is my string=NHUYT>".Trim();
var index = line.IndexOf("=") + 1;
var lastIndex = line.IndexOf(">");

var id = line.Substring(index, lastIndex - index);
Owen Pauling
  • 11,349
  • 20
  • 53
  • 64