OrdinaryKing
OrdinaryKing

Reputation: 451

C# Delete everything after a character but before another

Im working with a piece of dynamic data I need to remove some but not the final part of the string.

var x = "<abc><static string data> Data inside here is dynamic </abc>"

I want to be able to delete everything after string data, but keep the closing brackets of </abc>.

I can delete everything by doing;

x = x.Substring(0, x.IndexOf("<static string data>") + 1);

but that removes the </abc> part and I dont want to manually add </abc> back in as it defeats the point of what im trying to achieve.

Upvotes: 0

Views: 270

Answers (1)

E.J. Brennan
E.J. Brennan

Reputation: 46849

This could be done more gracefully, but for demonstration:

    var x = "<abc><static string data> Data inside here is dynamic </abc>";
    var start = x.IndexOf("<static string data>") + ("<static string data>").Length;
    var end = x.IndexOf("</abc>");

    var newStr = x.Substring(0, start) + x.Substring(end);
    Console.Writeline(newStr);

Output:

<abc><static string data></abc>

Upvotes: 2

Related Questions