在2个细节字符之间获取字符串



我想做一个应用程序。

在此应用程序中,我想在我选择的2个字符之间获得字符串。

示例:" Hello World"。

如果我选择了字符" e"one_answers" d",这将获得" llo worl"

我正在尝试帮助Microsoft文档中的子字符串方法。但是我找不到如何放置字符串的最后限制。

谢谢您的帮助

Dim MainString As String 'the main string 
Dim FirstChar As String 'first character
Dim lastchar As String 'second char
Dim finalastring As String 'final string after the work is done
Dim FirstCharIndex As Integer 'the index where first char is located
Dim LastCharIndex As Integer 'the index where last char is located
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    MainString = TextBox1.Text 'Hello World
    FirstChar = TextBox2.Text 'e
    lastchar = TextBox3.Text 'd
    FirstCharIndex = MainString.IndexOf(FirstChar) 'this will return 1 in this condition
    LastCharIndex = MainString.LastIndexOf(lastchar) 'this will return 10
    'now, Final String
    finalastring = MainString.Substring(FirstCharIndex, (LastCharIndex - FirstCharIndex))
    TextBox4.Text = finalastring

End Sub

您仍然可以使用Substring来完成:

    Public Sub Main()
        Dim test as String = "Hello World"
        Console.WriteLine(StringBetweenChars(test,"e","d"))
    End Sub
    Public Function StringBetweenChars(ByVal fullText, ByVal start, ByVal ending) as String
        Dim x,j as integer
        x = fullText.IndexOf(start) + 1
        j = fullText.IndexOf(ending) 
        If(j <> -1) Then
            return fullText.Substring(x, j-x)           
            Else
            return fullText.Substring(x, fullText.Length - x)
        End If
    End function

此打印出来: llo Worl

最新更新