Reputation: 445
Based in thisreplace multiple words by the same word in bold , I realised that this code has a problem/limitation ..
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();
}
With this line var words = text.Split(" ");
I´m separating all the words in the text, but what if the string I want to replace is :
Text: "I have a text and I need to put some words in bold"
Words: "have a text"; "bold"
Result : "I have a text and I need to put some words in bold"
EDIT ::
I updated my code like this
private string Bold(string text, string[] splitwords)
{
StringBuilder builder = new StringBuilder();
builder.Append(@"{\rtf1\ansi");
foreach (string word in splitwords)
{
if (Regex.IsMatch(text, @"(?<![\w])" + word + @"(?![\w])" ))
{
text= text.Replace(word, @"\b " + word + " " + @"\b0");
}
}
builder.Append(text);
builder.Append(@"}");
return builder.ToString();
}
But if the if I have the text
Text: "I have a text and I need to put some words in bold"
Words: "have"; "have a text"; "bold"
Result : "I have a text and I need to put some words in bold"
But in another cases it works fine HELP....
Upvotes: 0
Views: 2121
Reputation: 2062
Try this :
public string MakeBold(string text, string[] splitwords)
{
string returnValue = text;
foreach (var word in splitwords)
{
returnValue = returnValue.Replace(word, @"\b" + word + @"\b0");
}
var finalString = new StringBuilder();
finalString.Append(@"{\rtf1\ansi");
finalString.Append(returnValue);
finalString.Append(@"}");
return finalString.ToString();
}
Upvotes: 1
Reputation: 1198
We can check for all occurrences of each phrase:
StringBuilder builder = new StringBuilder();
string[] words = text.Split(" ");
foreach (string phrase in splitwords)
{
string[] phrasewords = phrase.Split(" ");
for (int i = 0; i < words.Length - phrasewords.Length; i++)
{
bool match = true;
for (int j = 0; j < phrasewords.Length; j++)
if (words[i] != phrasewords[j])
{
match = false;
break;
}
if (match)
{
builder.Append(@"\b" + phrase + @"\b0 ");
i += phrasewords.Length - 1;
}
else
builder.Append(words[i] + " ");
}
}
This won't work for overlapping phrases, e.g. "one two" and "two three".
Upvotes: 0