【问题标题】:VB.net get the first word after a specified stringVB.net获取指定字符串后的第一个单词
【发布时间】:2014-06-09 21:33:13
【问题描述】:

我只需要在指定字符串之后获取第一个单词,就像这样(伪):

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)

【问题讨论】:

  • 附注:请使用String.IndexOf 而不是InStr
  • 您需要在找到的索引之后寻找下一个单词边界。这可以是空格、任何类型的标点符号或您定义的任何内容。

标签: vb.net string split substring


【解决方案1】:
    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**

【讨论】:

  • 这个答案可能是正确的,并提供了问题的解决方案。但是您可以添加它如何解决问题的说明,以便未来的读者可以了解它是如何工作的。
  • 当我运行它时,s 返回为“Open”。我错过了什么吗?
  • 你可以去掉open这个词前面的括号...因为s会返回括号后面的内容...
【解决方案2】:

这也有效。

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

【讨论】:

    【解决方案3】:

    试试这个:

    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
    

    【讨论】:

      猜你喜欢
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-07
      • 2022-12-18
      • 2012-11-24
      • 1970-01-01
      • 2011-04-02
      相关资源
      最近更新 更多