Wednesday, October 25, 2006

Remove Characters from a String with limited Memory

How about, If we don't have enough memory we have to use a single array.
Here is how to do that with limited memory


public static string RemoveCharactersLimited(char[] s, string removeChars)
{
int i = 0, j = 0;

int lengthC = removeChars.Length;
int lengthS = s.Length;
int[] intCollection = new int[256];

for (i = 0; i < lengthC; i++)
{
intCollection[removeChars[i]] = 1;
}

i = j = 0;
for (i = 0; i < lengthS; i++)
{
if (intCollection[s[i]] != 1)
{
s[j] = s[i];
j++;
}
}
while (j < lengthS)
{
s[j] = '\0';
j++;
}

return new string(s);

}

No comments: