I am having two string builders in which one holds the complete data and the other holds the data that should be replaced but I am unable to replace the content.
This is the code i have written
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
sb1.AppendLine("1111111111");
sb1.AppendLine("555555555");
sb1.AppendLine("666666660");
sb1.AppendLine("6666666601");
sb1.AppendLine("6666666602");
sb1.AppendLine("6666666603");
sb1.AppendLine("888888888");
sb1.AppendLine("99999999");
sb1.AppendLine("555555555");
sb1.AppendLine("666666661");
sb1.AppendLine("666666662");
sb1.AppendLine("666666663");
sb1.AppendLine("666666664");
sb1.AppendLine("888888888");
sb1.AppendLine("99999999");
sb2.AppendLine("6666666601");
sb2.AppendLine("666666661");
sb1 = sb1.Replace(sb2.ToString().TrimEnd(charRemove), "");
sb1 = sb1.Replace(sb2.ToString(), ""); // this also i tried
I would like to remove sb2 content
You mustn’t use
StringBuilderfor sb2.To make it short, you are telling .NET to replace
6666666601666666661insb1.Try:
(and I’m not even sure you want to use a
StringBuilderfor sb1.StringBuilderis used to “compose” strings, not to “collect” them)Note that this is still wrong wrong wrong!
You would be much better to begin the sb1 with an empty line, like this:
so that you can Replace like this:
in this way,
99won’t mach1999, because1999will be\r\n1999\r\nwhile99will be\r\n99\r\n(we are adding a blank line at the beginning of theStringBuilderso that even the first element is preceeded by a\r\n. We are replaceing with\r\nbecause we are matching TWO\r\n, one before and one later, but one of the two must be preserved.)I’ll add that perhaps you simply exchanged
StringBuilderfor a collection ofstrings, and perhaps you wanted to do this: