我想只从字符串中获取字母。 例如。 可以说字符串是这样的:123abc456d 我想得到:abcd 寻找类似这样的东西,但字符串中的字母:
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
由于
答案 0 :(得分:1)
你可以这样做:
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)
或:
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)
两者都会给你相同的结果。
希望对你有所帮助:)
答案 1 :(得分:0)
您可以使用Regex解决此问题。这个正则表达式基本上表示任何不在这个类中的东西,该类是字母表中的字母,然后通过替换它来删除。
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
确保在代码顶部Imports System.Text.RegularExpressions
答案 2 :(得分:0)
这是LINQ one liner:
Debug.Print(String.Concat("123abc456d".Where(AddressOf Char.IsLetter)))
结果:abcd
。
这里,.Where(AddressOf Char.IsLetter)
将字符串视为字符列表,并且只保留列表中的字母。然后,String.Concat
通过连接字符重新构建字符串中的字符串。