开发者

Position of character to the left of current position in string

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 just use .IndexOf, but how to do it to the left I am unsure.

The two ways I came up with were just a decrementing loop starting at my position or, putting the string in reverse and using a normal .IndexOf

Anyone else have any better ways of achieving this?


What about:

yourstring.LastIndexOf("foo", 0, currentPosition)                                  


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜