0
string keywords = "heard";
string strText = "Have you not heard!! what I said?"
string[] words = strText.Split(' ');
string result = "";

for (int i = 0; i < words.Length; i++)
{
   if (words[i].Contains(keywords))
    result += "<span>" + words[i] + "</span>" + " ";
   else
    result += words[i] + " ";
}

I get following output:

Have you not <span>heard!!</span> what I said?

Desired output:

Have you not <span>heard</span>!! what I said?

Can someone guide how can I get the desired output. The strText can only be split with a space.

1
  • 2
    What javascript tag does here? Commented Aug 7, 2014 at 8:27

2 Answers 2

2

Use String.Replace

var result = strText.Replace(keywords, "<span>" + keywords + "</span>");

If you have many keywords to replace, then just do replacement in a loop:

string[] keywords = { "heard", "said" };
string result = "Have you not heard!! what I said?";

foreach(var keyword in keywords)
    result = result.Replace(keyword, "<span>" + keyword + "</span>");

Alternative solution is regular expression replacement:

string keywords = "heard|said";
string result = "Have you not heard!! what I said?";
result = Regex.Replace(result, keywords, m => "<span>" + m.Value + "</span>");
Sign up to request clarification or add additional context in comments.

2 Comments

@mrd thanks) but I decided it would be overkill for simple replacement task)
m => "<span>" + m.Value + "</span>" can be replaced by "<span>$0</span>".
0

Why are you even looping through all words? This will give you the same:

        string strText = "Have you not heard!! what I said?";
        string newText = strText.Replace("heard", "<span>heard</span>");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.