用粗体的同一个词替换多个词 [英] replace multiple words by the same word in bold

查看:70
本文介绍了用粗体的同一个词替换多个词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 RichTextBox 中有一个文本和一个单词列表(wordList) - 我正在使用 winforms.
我需要做的是所有单词列表中的单词都以粗体显示在文本中.
示例:
文本:我有一个文本,我需要将一些单词加粗"

I have a text in a RichTextBox, and a list of words(wordList) - I´m using winforms.
What I need to do is all the words that are in the wordList appear in the text in bold.
Example :
Text: "I have a text and I need to put some words in bold"

列表中的单词:"need";一些";粗体"

结果:我有一个文本,我需要一些字放在粗体中"
我试过了(我在 stackoverflow 中看到了类似的帖子)

Result : "I have a text and I need to put some words in bold"
I tried this ( I saw a similar post here in stackoverflow)

text= "" + text+ "";

foreach (var word in wordList)
{
    string w = string.Format(" {0} ", word);
    if (text.Contains(w))
    {
        while (text.Contains(w))
        {
            text= text.Replace(w, "<b>"+w+"</b>");
        }
    }
}

text = text.Trim();

如何说 w 需要加粗?

How can I say that the word w need to be in bold?


我试过这个解决方案


I tried this solution

  public string MakeBold(string text, string[] splitwords)
  {
      var sb = new StringBuilder();
      var words = text.Split(' ');
      sb.Append(@"{\rtf1\ansi ");
      foreach (var word in words)
      {
          if (splitwords.Contains(word))
          {
              sb.Append(@"\b" + word + @"\b0");
          }
          else
          {
              sb.Append(word);
              sb.Append(@" ");
          }
      }
      sb.Append(@"}");
      return sb.ToString();
  }

结果在 RichTextBox 中

and the result is in the RichTextBox

{\rtf1\ansiI have a text and I \bneed\b0to put \bsome\b0words in \bbold\b0}    

任何想法为什么??

推荐答案

您似乎将 Web 与富文本框混淆了.示例代码仅对空格进行拆分,对大写字母不做任何处理.

It seems you are confusing web with a rich text box. The sample code only splits on spaces, and does not do anything with Capitals.

public string MakeBold(string text, string[] splitwords)
{
    var sb = new StringBuilder();
    var words = text.Split(" ");   
    sb.Append(@"{\rtf1\ansi");
    foreach (var word in words){
      if (splitwords.Contains(word)){
         sb.Append(@"\b"+word+ @"\b0 ");
      }
      else
      {
         sb.Append(word);
         sb.Append(@" ");
      }
    }
    sb.Append(@"}");
    return sb.ToString();
}

这篇关于用粗体的同一个词替换多个词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆