繁体   English   中英

搜索字符串中的句子(C#)

[英]Search a sentence in a string (C#)

我的问题分为两部分:

1)如何搜索字符串中的句子(例如, Dell Canada )(例如, I am working in Dell Canada ,我找到了...)。

2)第二部分是我的字符串是RichTextBox中的文本,因此我想找到该选定句子的TextRange并应用某些修饰。

谢谢。

旋转一下,它将设置为粗体。 您可以使用RichTextBox上的许多Selection ...属性,还请注意,这是不区分大小写的搜索:

    string textToSearchFor = "Dell Canada";
    int index = richTextBox1.Text.IndexOf(textToSearchFor, StringComparison.OrdinalIgnoreCase);
    if (index >= 0)
    {
        richTextBox1.Select(index, textToSearchFor.Length);
        richTextBox1.SelectionFont = new Font("Arial", 12f, FontStyle.Bold);
    }
    else
    {
        // not found
    }

第1部分:

if (myString.IndexOf("Dell Canada") > -1)
{
    // do something great;
}

第1部分。

bool cntns = "I am working in Dell Canada, and found it ...".Contains("Dell Canada")

正如CK指出的那样,第一部分非常简单。 RTF规范中定义的某些预定义代码决定了RTF格式。 首先使用RTF属性从控件中获取基础RTF原始字符串

字符串rawString = richTextBox.Rtf;

例如:短语“ hello Bobby”的rtf如下所示。 就像HTML一样,您具有定义格式的标签。

"{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Microsoft Sans Serif;}}\r\n\\viewkind4\\uc1\\pard\\f0\\fs17 hello Bobby\\par\r\n\\par\r\n}\r\n"

现在假设我想将短语设为粗体,我将通过将字符串替换为Rtf来设置Rtf属性。

"{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Microsoft Sans Serif;}}\r\n\\viewkind4\\uc1\\pard\\f0\\fs17
\\b hello Bobby\\par\r\n\\par\r\n}\r\n"

注意短语前的\\\\ b。 这就是将给定文本加粗的代码。

要使用代码执行此格式化,请找到要格式化的字符串(使用第一种技术),然后将rtf代码插入所需的位置。 希望这可以帮助。

有关代码,请参阅MSDN http://msdn.microsoft.com/zh-cn/library/aa140277.aspx

PS:杰夫的版本很简单。 此版本为您提供了无限的控制权。 如果可以在写字板中执行某些操作,则可以使用rtf代码执行相同的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM