木子屋 Dnawo's BLOG

RichTextBox.Find遍历搜索字符串中的坑

👤 dnawo 📅 2014-12-24 👁 6045 👍 0 💬 0 🔄 来源:本站原创
RichTextBox.Find遍历搜索字符串有两个重载方法可供调用:

public int Find(string str, int start, RichTextBoxFinds options);
public int Find(string str, int start, int end, RichTextBoxFinds options);

经测试发现:在特定场合下这两个重载方法可能发生死循环,下面分别举栗说明。

例1:Find(string str, int start, RichTextBoxFinds options)重载

int index = -1;
while ((index = richTextBox1.Find("屋", index + 1, RichTextBoxFinds.MatchCase)) != -1)
{
    MessageBox.Show(index.ToString());
}

当richTextBox1.Text="木子屋"时,即搜索的字符串在最后一位时会发生死循环,MSDN没有说明start参数值等于RichTextBox.Text.Length时(大于会出错)会从头开始搜索。

例2:public int Find(string str, int start, int end, RichTextBoxFinds options)重载

int index = -1;
while ((index = richTextBox1.Find("屋", index + 1, richTextBox1.Text.Length-1, RichTextBoxFinds.MatchCase)) != -1)
{
    MessageBox.Show(index.ToString());
}

当richTextBox1.Text="木屋子"时,即搜索的字符串在倒数第二位时会发生死循环,这在MSDN有相关说明:

当给 start 和 end 参数提供相同的值时,就会搜索整个控件(正常搜索)。

若将end参数值改为-1,则又会出现例1的情况。

目前的解决方法是在循环内部加判断,出现上面栗子的情况时退出循环:

int index = -1;
while ((index = richTextBox1.Find("屋", index + 1, RichTextBoxFinds.MatchCase)) != -1)
{
    MessageBox.Show(index.ToString());
    if (index + 1 == richTextBox1.Text.Length)
    {
        break;
    }
}

相关链接

[1].RichTextBox.Find 方法 (String, Int32, RichTextBoxFinds):http://msdn.microsoft.com/zh-cn/library/9be0980x(v=vs.100).aspx
[2].RichTextBox.Find 方法 (String, Int32, Int32, RichTextBoxFinds):http://msdn.microsoft.com/zh-cn/library/yab8wkhy(v=vs.100).aspx

评论(0)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 PJBlog3 V3.2.9.518可恶意注册BUG解决方法 下一篇 → 表达式树ExpressionTree[转]