I'm attempting to write a piece of code that is supposed to remove consecutive appearances of a string (not a single character) in a StringBuilder.
It's extremely important that the method works well and does not remove or change anything that it shouldn't. Solid performance is a secondary requirement.
for example:
Input: "xxxxABCxxxxABCABCxxxxABABCxxABCABCABC"
Remove consecutive: "ABC"
Output: "xxxxABCxxxxABCxxxxABABCxxABC"
I've written a method that does this and testing shows that it works as expected, but it will be catastrophic if I use it and it results in changing the StringBuilder in an unexpected way - that's why I want another opinion on whether my code is really 'safe' in all cases:
public static void RemoveConsecutive(this StringBuilder sb, string value)
{
if (sb == null)
throw new ArgumentNullException("sb");
if (value == null)
throw new ArgumentNullException("value");
if (value == string.Empty)
throw new ArgumentException("value cannot be an empty string.", "value");
bool justRemoved = false;
for (int i = 0; i < sb.Length - value.Length; i++)
{
if (justRemoved || Util.ExistsAt(sb, i, value))
{
if (Util.ExistsAt(sb, i + value.Length, value))
{
sb.Remove(i, value.Length);
justRemoved = true;
i--;
}
else
{
justRemoved = false;
}
}
}
}
// Checks if the provided string appears in the StringBuilder at the specified index
public static bool ExistsAt(StringBuilder sb, int startIndex, string str)
{
if (startIndex < 0 || startIndex >= sb.Length)
throw new ArgumentOutOfRangeException("startIndex", "startIndex must be a valid index in the provided StringBuilder.");
if (startIndex + str.Length > sb.Length)
return false;
for (int i = 0; i < str.Length; i++)
{
if (str[i] != sb[i + startIndex])
return false;
}
return true;
}
While this piece of code does something rather trivial, I just want another set of eyes to look at it and possibly find faults I could not. Again, any sort of unexpected behavior might be catastrophic.
"xxxxABCxxxxABCABCxxxxABABCxxABCABCABC" -> "xxxxABCxxxxABCxxxxABABCxxABC". But (replacing yourxs with digits for visibility) shouldn't that result be0123ABC45678901ABABC23? – Ross Patterson Feb 10 at 13:47ABCyou removed were not consecutive. – svick Feb 10 at 13:57