VB.net获取指定字符串后的第一个单词

时间:2014-04-24 14:19:04

标签: vb.net string split substring

我需要在指定的字符串之后得到第一个字,如此(伪):

my_string = "Hello Mr. John, how are you today?"
my_search_string = "are"
result = "you"

我尝试使用以下方法来完成它,但是在我的"键"之后我得到了其余的字符串。字符串,而不是一个单词。

    Dim search_string As String = "key"
    Dim x As Integer = InStr(Textbox1.text, search_string)

    Dim word_after_key As String = Textbox1.text.Substring(x + search_string.Length - 1)

3 个答案:

答案 0 :(得分:2)

试试这个:

Dim str = "Hello Mr. John, how are you today?"
Dim key = " are "
Dim i = str.IndexOf(key)
If i <> -1 Then
    i += key.Length
    Dim j = str.IndexOf(" ", i)
    If j <> -1 Then
        Dim result = str.Substring(i, j - i)
    End If
End If

或许这可能:

Dim str = "Hello Mr. John, how are you today?"
Dim key = "are"
Dim words = str.Split(" "C)
Dim i = Array.IndexOf(words, key)
If i <> -1 AndAlso i <> words.Length - 1 Then
    Dim result = words(i + 1)
End If

答案 1 :(得分:0)

这也有效。

Dim my_string as String = "Hello Mr. John, how are you today?"
Dim SearchString As String = "are"
Dim StartP As Integer = InStr(my_string, SearchString) + Len(SearchString) + 1 
' to account for the space

If StartP > 0 Then
    Dim EndP As Integer = InStr(StartP, my_string, " ")
    MsgBox(Mid(my_string, StartP, EndP - StartP))
End If

答案 2 :(得分:-2)

    Dim sa As String
    Dim s As String
    Dim sp() As String
    sa = TextBox1.Text 'this text box contains value **Open Ended Schemes(Debt Scheme - Banking and PSU Fund)**
    sp = sa.Split("(") 'Here u get the output as **Debt Scheme - Banking and PSU Fund)** which means content after the open bracket...
    sp = sp(1).Split(")") 'Here u get the output as Debt Scheme - Banking and PSU Fund which means content till the close bracket...
    s = Split(sp(0))(0) 'Here it will take the first word, which means u will get the output as **Debt**
    s = Split(sp(0))(1) 'Change the index as per the word u want, here u get the output as **Scheme**