Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# Find occurrences of string within a string and wrap text around the matching chars

Split string, example here

 var hello = "Hello World";

I’m trying to get the result to be "Hello World" with spans around the matching "l"

    string[] words = hello.ToLower().Split("l");
    var resultString = "";
    
    for (int i = 0; i < words.Length; i++)
    {
        // now we have split the string how do find the missing 'l' and wrap a span around them
        resultString += words[i].ToString();
    }
    // result is heo word
    Console.WriteLine(resultString);
    // Trying to get the result to be "He<span>l</span><span>l</span>o Wor<span>l<span>d

see dotnetfiddle

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

var result = Regex.Replace(hello, "l", x => $"<span>{x}</span>");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading