我正忙着写过去的试卷,为下周的 vb.net 考试做准备。我正在努力解决的问题如下。
取一长串字母字符和特殊字符,将字母字符提取到string1,将特殊字符提取到string2
所以字符串 hello://thisismystring!? 必须显示如下
string1 = hellothisismystring
string2 = ://!?
我的问题是如何从字符串中提取字符并将它们存储在变量中?
一种对 Unicode 友好、干净且简单的方式。
Imports System.Text
Module Module1
Sub Main()
Dim sValue As String = "hello://thisismystring!?"
Dim a As New StringBuilder
Dim b As New StringBuilder
For Each c As Char In sValue
If Char.IsLetter(c) Then
a.Append(c)
Else
b.Append(c)
End If
Next
Dim s1 As String = a.ToString()
Dim s2 As String = b.ToString()
End Sub
End Module
您可以遍历该字符串中的字符,并使用 ASCII 代码来确定当前字符是否为字母,如果是 -> string1,如果不是 -> string2。祝你好运。
这是一种方法
Dim allText As String = "Hello139874098@#4this204985"
Dim onlyLetters As String = ""
Dim nonLetters As String = ""
For i = 0 To allText.Length - 1
Dim c As String = allText.Substring(i, 1)
If c.ToUpper >= "A" And c.ToUpper <= "Z" Then
onlyLetters &= c
Else
nonLetters &= c
End If
Next
MsgBox("Letters are " & onlyLetters)
MsgBox("Non-Letters are " & nonLetters)
我会用这个:
Dim SearchString = "hello://thisismystring!?"
Dim ToFind = "://!?"
Dim ResultSpecial As String = ""
Dim ResultNormal As String = ""
Dim ChrList As New List(Of Char)
For Each c In ToFind
ChrList.Add(c)
Next
For i = 0 To SearchString.Length - 1
Dim c = SearchString(i)
If ChrList.Contains(c) = True Then
ResultSpecial = ResultSpecial & c
Else
ResultNormal = ResultNormal & c
End If
Next
Debug.Print("Resultnormal: " & ResultNormal)
Debug.Print("ResultSpecial: " & ResultSpecial)
您必须将所有需要的字符写入“ToFind” 正则表达式会更好,但它们有时很麻烦......
Module Module1
Sub Main()
Dim SearchString = "hello://thisismystring!?"
Dim ToFind = "://!?"
Dim ResultSpecial As String = ""
Dim ResultNormal As String = ""
For Each c In SearchString
If ToFind.Contains(c) Then
ResultSpecial = ResultSpecial + c
Else
ResultNormal = ResultNormal + c
End If
Next
Debug.WriteLine(ResultNormal, "Resultnormal")
Debug.WriteLine(ResultSpecial, "ResultSpecial")
End Sub
End Module