patternMinor
Extract numbers from an AlphaNumeric string
Viewed 0 times
numbersalphanumericextractfromstring
Problem
I have an alphanumeric string like
The message box will display
For extracting letters from the same string, I use the following:
Is this a better way to extract both?
sdff45hg589>@#DF456&<jk778P&&FHJ75, of which I want to extract only the numbers, without using regex or any other functions. Dim input As String = "sdff45hg589>@#DF456&<jk778P&&FHJ75"
Dim output As String = New String((From c As Char In input Select c Where Char.IsDigit(c)).ToArray())
MsgBox(output) 'Display the outputThe message box will display
4558945677875.For extracting letters from the same string, I use the following:
Dim input As String = "sdff45hg589>@#DF456&<jk778P&&FHJ75"
Dim output As String = New String((From c As Char In input Select c Where Char.IsLetter(c)).ToArray())
MsgBox (output)Is this a better way to extract both?
Solution
If you want to extract both at the same time (I don't know if it is a requirement, it isn't clear in the question) you should iterate once through each character to place them in different lists.
Edit
As pointed out @mjolka, since the goal of the user is to show the splitted numbers and letters, a
Dim input As String = "sdff45hg589>@#DF456&<jk778P&&FHJ75"
Dim characters As List(Of Char) = New List(Of Char)()
Dim numbers As List(Of Char) = New List(Of Char)()
For Each c As Char In input
If (Char.IsNumber(c)) Then
numbers.Add(c)
ElseIf (Char.IsLetter(c)) Then
characters.Add(c)
End If
Next
'Do whatever you have to do hereEdit
As pointed out @mjolka, since the goal of the user is to show the splitted numbers and letters, a
StringBuilder would be more appropriate. Here is my updated answer : Dim input As String = "sdff45hg589>@#DF456&<jk778P&&FHJ75"
Dim characters As StringBuilder = New StringBuilder()
Dim numbers As StringBuilder = New StringBuilder()
For Each c As Char In input
If (Char.IsNumber(c)) Then
numbers.Append(c)
ElseIf (Char.IsLetter(c)) Then
characters.Append(c)
End If
Next
'Do whatever you have to do hereCode Snippets
Dim input As String = "sdff45hg589>@#DF456&<jk778P&&FHJ75"
Dim characters As List(Of Char) = New List(Of Char)()
Dim numbers As List(Of Char) = New List(Of Char)()
For Each c As Char In input
If (Char.IsNumber(c)) Then
numbers.Add(c)
ElseIf (Char.IsLetter(c)) Then
characters.Add(c)
End If
Next
'Do whatever you have to do hereDim input As String = "sdff45hg589>@#DF456&<jk778P&&FHJ75"
Dim characters As StringBuilder = New StringBuilder()
Dim numbers As StringBuilder = New StringBuilder()
For Each c As Char In input
If (Char.IsNumber(c)) Then
numbers.Append(c)
ElseIf (Char.IsLetter(c)) Then
characters.Append(c)
End If
Next
'Do whatever you have to do hereContext
StackExchange Code Review Q#59488, answer score: 3
Revisions (0)
No revisions yet.