Reputation: 1
i want to get only letters from string. eg. Lets say the string is this :123abc456d I want to get: abcd Looking for something like this but for letters in a string:
Dim mytext As String = "123a123"
Dim myChars() As Char = mytext.ToCharArray()
For Each ch As Char In myChars
If Char.IsDigit(ch) Then
MessageBox.Show(ch)
End If
Next
Thanks
Upvotes: 0
Views: 3637
Reputation: 654
You can use Regex to solve this problem. This regex basically says anything that is not in this class, the class being letters in the alphabet then remove by replacing it with nothing.
Dim mytext As String = "123a123"
Dim Result as String = Regex.Replace(myText, "[^a-zA-Z]", "")
Dim myChars() As Char = Result.ToCharArray()
For Each ch As Char In myChars
If Char.IsDigit(ch) Then
MessageBox.Show(ch)
End If
Next
Make sure you have this at the top of your code Imports System.Text.RegularExpressions
Upvotes: 1
Reputation: 626748
Here is a LINQ one liner:
Debug.Print(String.Concat("123abc456d".Where(AddressOf Char.IsLetter)))
Result: abcd
.
Here, .Where(AddressOf Char.IsLetter)
treats the string as a list of chars, and only keeps letters in the list. Then, String.Concat
re-builds the string out of the char list by concatenating the chars.
Upvotes: 1
Reputation: 1290
You can do it like this :
Dim mytext As String = "123a123"
Dim RemoveChars As String = "0123456789" 'These are the chars that you want to remove from your mytext string
Dim FinalResult As String
Dim myChars() As Char = mytext.ToCharArray()
For Each ch As Char In myChars
If Not RemoveChars.Contains(ch) Then
FinalResult &= ch
End If
Next
MsgBox(FinalResult)
OR :
Dim mytext As String = "1d23ad123d"
Dim myChars() As Char = mytext.ToCharArray()
Dim FinalResult As String
For Each ch As Char In myChars
If Not Char.IsDigit(ch) Then
FinalResult &= ch
End If
Next
MsgBox(FinalResult)
Both will give you the same result.
Hope that helped you :)
Upvotes: 1