Position of character to the left of current position in string

后端 未结 2 1955
一向
一向 2021-01-26 19:28

From some arbitrary position in a string I need to find the closest position of a character to the left of my position. If I want to perform this operation to the right I could

相关标签:
2条回答
  • 2021-01-26 20:08

    What about:

    yourstring.LastIndexOf("foo", 0, currentPosition)                                  
    
    0 讨论(0)
  • 2021-01-26 20:16

    More explicitly, find word occurring before nWord in txt: Your word will be at position s:

    Dim s As Integer = txt.Substring(0, txt.IndexOf(nWord)).LastIndexOf(word)
    

    This was useful to me in a loop where I needed to find all occurrences.

    This is how to construct the loop:

    Dim n As Integer = 0
    Dim s As Integer = 0
    Do While txt.Contains(word) AndAlso txt.Contains(nWord)
         n = txt.IndexOf(nWord)
         'n = txt.IndexOf(nWord)+nWord.Length ':If nWord may also contain word
         s += txt.Substring(0, n).LastIndexOf(word)
         txt = txt.SubString(n + nWord.Length)
         MsgBox("Found at " & s.ToString())
    Loop
    
    0 讨论(0)
提交回复
热议问题