如何向后搜索请求的文本?

时间:2014-11-13 06:11:23

标签: c# winforms

转到记事本。输入“这是一个测试,这是一个测试,这是一个测试”。将插入符号放在文本的最后。转到编辑 - >查找 - >输入“是” - >将方向设置为“向上”。

每种类型点击“查找下一个”,选择插入符号之前的“是”。然后,在下次输入“Find Is”时,选择先前的“is”。

如何使用WinForm的文本框以类似的方式在代码中执行此操作?我真的不明白如何向后搜索某些字符串。感谢。

2 个答案:

答案 0 :(得分:2)

使用 String.LastIndexOf(string value, int startIndex) 方法。

此方法开始在字符串的startIndex字符位置搜索,然后向后朝向开头搜索,直到找到value或检查到第一个字符位置。

答案 1 :(得分:0)

由于您显然正在实施实际搜索框,因此此代码可能会对您有所帮助。它旨在完全模拟记事本搜索选项,包括当前光标位置,大小写(in)灵敏度和前向/后向搜索。它将自动环绕到文件的开头,然后在光标前搜索文本(而向后搜索则相反)。

    protected Int32 DoSearch(ref String sourceText, String findText, Int32 searchStartPos, StringComparison sc, Boolean forward)
    {
        Int32 resultPos = -1;
        if (forward)
        {
            // Makes sure that if the cursor is currently ON a result, then the next result is found.
            // Not needed for backwards search, since you search before the current position in that case.
            if (sourceText.Length - findText.Length >= searchStartPos && findText.Equals(sourceText.Substring(searchStartPos, findText.Length), sc))
                searchStartPos++;

            resultPos = sourceText.IndexOf(findText, searchStartPos, sc);
            if (resultPos == -1)
                resultPos = sourceText.IndexOf(findText, 0, searchStartPos, sc);
        }
        else
        {
            resultPos = sourceText.LastIndexOf(findText, searchStartPos, sc);
            if (resultPos == -1)
            {
                Int32 start = sourceText.Length;
                Int32 length = start - searchStartPos;
                resultPos = sourceText.LastIndexOf(findText, start, length, sc);
            }
        }
        return resultPos;
    }

请注意,sourceText仅由于在函数调用时复制了一个普通的字符串变量而被引用处理,这在这里完全浪费时间;文本可能相当大,而且这个函数永远不会修改字符串,所以传递一个指针对我来说似乎更有效。

(在我的完整代码中,这在我的搜索框代码的其余部分进一步优化,TextChanged事件评估是否必须从文本框中重新提取文本)

此搜索通常后面是代码选择相关部分,使用返回的resultPos作为选择开始,findText.Length作为选择长度。