[英]Extracting characters from a string in vb.net
我正忙於處理過去的考試卷,為下周的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)
您必須將所有所需的Character寫入“ 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.