Removes all characters from variable String but letters

advertisements

This question already has an answer here:

  • How do I remove all non alphanumeric characters from a string except dash? 9 answers

I want to write a function that removes all characters in a string variables but leaves only the letters.

For example, if the string variable has

"My'na/me*is'S.oph&ia."

I want to display

"My name is Sophia"

What is the simplest way to do this?


Convert the String to a character array, like this:

Dim theCharacterArray As Char() = YourString.ToCharArray()

Now loop through and keep only the letters, like this:

theCharacterArray = Array.FindAll(Of Char)(theCharacterArray, (Function(c) (Char.IsLetter(c))))

Finally, convert the character back to a String, like this

YourString = New String(theCharacterArray)

Note: This answer is a VB.NET adaptation of an answer to How to remove all non alphanumeric characters from a string except dash.