0

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?

HelpASisterOut
  • 3,085
  • 16
  • 45
  • 89
  • 2
    Have a look at this question: http://stackoverflow.com/questions/3210393/how-to-remove-all-non-alphanumeric-characters-from-a-string-except-dash – Paul Michaels Sep 23 '13 at 14:54

2 Answers2

2

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.

Community
  • 1
  • 1
Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
  • 1
    The only problem is that is removes white-spaces, so the result is `"MynameisSophia"` instead of `"My name is Sophia"`. – Tim Schmelter Sep 23 '13 at 15:11
  • @TimSchmelter - I understand, but the original string did not have white-space, so how can I preserve something that did not exist? – Karl Anderson Sep 23 '13 at 15:42
  • Ok, one step more missing, this does not replace the characters `'` and `*` with white-space as desired. However, i assume OP has simply provided a bad example. – Tim Schmelter Sep 23 '13 at 15:45
1

So you want to replace ' and * with white-spaces and then remove all non-letters?

Dim lettersOnly = From c In "My'na/me*is'S.oph&ia.".
                  Replace("'"c, " "c).Replace("*"c, " "c)
                  Where Char.IsWhiteSpace(c) OrElse Char.IsLetter(c)
Dim result As New String(lettersOnly.ToArray())
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939