【问题标题】:Position of character to the left of current position in string字符串中当前位置左侧的字符位置
【发布时间】:2011-01-02 12:43:27
【问题描述】:

我需要从字符串中的某个任意位置找到离我的位置最近的字符位置。如果我想在右侧执行此操作,我可以使用.IndexOf,但我不确定如何在左侧执行此操作。

我想出的两种方法只是从我的位置开始递减循环,或者将字符串反转并使用普通的.IndexOf

还有其他人有更好的方法来实现这一点吗?

【问题讨论】:

    标签: c# string indexing


    【解决方案1】:

    怎么样:

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

    【讨论】:

    • 那怎么样,这是我正在努力的一个更简单的解决方案。
    【解决方案2】:

    更明确地说,在 txt 中找到出现在 nWord 之前的 word:您的单词将位于 s 位置:

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

    这在我需要查找所有匹配项的循环中很有用。

    这是构造循环的方法:

    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
    

    【讨论】:

      猜你喜欢
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多