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);

}

Remove Characters from String C#.NET

The string manipulation function removes a set of characters fromthe input string

For example

Removing "RT" from "ROBERT FROST" will give you "OBE FOS"


public static string RemoveCharacters(string s, string removeChars)
{
int i=0,j=0;

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

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

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

return new string(s2);

}