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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The only problem is that is removes white-spaces, so the result is "MynameisSophia" instead of "My name is Sophia".
@TimSchmelter - I understand, but the original string did not have white-space, so how can I preserve something that did not exist?
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.
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())

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.