Stripping a String variable of any non-numeric or non-alphacharacters?

  • Thread starter Thread starter Joe Cool
  • Start date Start date
J

Joe Cool

I am working on converting a program I originally wrote in VB.NET to
C#.NET. One thing it needs to do is to take a string variable and
remove any characters that are not numeric or alpha (either lower or
upper). WIth VB.NET this was easy since VB.NET has an Asc function.
But C#.NET doesn't. I would prefer to leave this app as 100% C#.NET,
no VB.NET class library, and no usage of the Microsoft.VisualBasic
namespace.

And suggestions on how to accomplish this?
 
I am working on converting a program I originally wrote in VB.NET to
C#.NET. One thing it needs to do is to take a string variable and
remove any characters that are not numeric or alpha (either lower or
upper). WIth VB.NET this was easy since VB.NET has an Asc function.
But C#.NET doesn't. I would prefer to leave this app as 100% C#.NET,
no VB.NET class library, and no usage of the Microsoft.VisualBasic
namespace.

And suggestions on how to accomplish this?

I would do that with Regex.Replace in both C# and VB.NET !

And does Asc really do something that indexing and cast
to int does not do?

Arne
 
I am working on converting a program I originally wrote in VB.NET to
C#.NET. One thing it needs to do is to take a string variable and
remove any characters that are not numeric or alpha (either lower or
upper). WIth VB.NET this was easy since VB.NET has an Asc function.
But C#.NET doesn't. I would prefer to leave this app as 100% C#.NET,
no VB.NET class library, and no usage of the Microsoft.VisualBasic
namespace.

And suggestions on how to accomplish this?

The equivalent of Asc() is simply casting a char into int (or short, if you
prefer).
 
I would do that with Regex.Replace in both C# and VB.NET !

And does Asc really do something that indexing and cast
to int does not do?

Does casting a string character to int do the same thing the VB Asc
function does? If so, I was unaware of that.
 
Does casting a string character to int do the same thing the VB Asc
function does?

I am not a VB expert, but I think for this purpose it will.

(I am not quite sure how it handles chars over \u007F)

Arne
 
Joe Cool said:
I am working on converting a program I originally wrote in VB.NET to
C#.NET. One thing it needs to do is to take a string variable and
remove any characters that are not numeric or alpha (either lower or
upper). WIth VB.NET this was easy since VB.NET has an Asc function.
But C#.NET doesn't. I would prefer to leave this app as 100% C#.NET,
no VB.NET class library, and no usage of the Microsoft.VisualBasic
namespace.

And suggestions on how to accomplish this?

Regular expressions are the way to handle this.

Regex.Replace(yourstring, "[^a-zA-Z0-9]", "");
 
Back
Top