Free Information Technology Magazines and eBooks

Thursday, June 04, 2009

C#: How to remove Characters from String

A common friend emailed me yesterday asking for help. He is a VB.NET beginner who wants to try C# programming. His request is a sample source code that demonstrate how to remove characters from string. Below is a string manipulation source code that I previously used on my old project, I tweaked it a little bit to fit his requirement.



The following sourcecode can strip charaters from string. For example: removing "F9" from "FRYAN0911" will give you "RYAN011"


public static string RemoveChars(string s, string myChars)
{
int i = 0, j = 0;

int CharLength = myChars.Length;
int StringLength = s.Length;
int[] intCollection = new int[256];
char[] s2 = new char[StringLength];

for (i = 0; i < CharLength; i++)
{
intCollection[myChars[i]] = 1;
}

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

return new string(s2);

}


For more C# coding tips, subscribe now

3 comments:

Wrecks said...

http://awesvb.blogspot.com/2009/06/remove-embedded-dashes-from-number.html

Anonymous said...

Why not use string.Replace()?

Fryan Valdez said...

Because string.Replace() can only strip 1 character at a time. How about if you need to remove 20 different character in a string? You will have to call string.Replace() 20x.