从vb.net中的字符串中提取字符

时间:2012-11-06 06:23:54

标签: vb.net string character extract

我正在忙着处理过去的考试试卷,为下周的vb.net考试做准备。我正在努力解决的问题如下。

接受一长串字母字符和特殊字符 将字母字符提取到string1并将特殊字符提取到string2

所以字符串hello:// thisismystring!?必须显示如下

string1 = hellothisismystring
string2 = ://!?

我的问题是如何从字符串中提取字符并将其存储在变量中?

4 个答案:

答案 0 :(得分:3)

一种非常友好,简洁的方式。

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

答案 1 :(得分:0)

您可以遍历该字符串中的字符,并使用ASCII代码确定当前字符是否为字母,如果是 - > string1,如果没有 - >字符串2。祝你好运。

答案 2 :(得分:0)

这是一种方法

    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)

答案 3 :(得分:0)

我会用这个:

    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