Search code examples
c#listreplaceindexof

Replace List of string into an existing string C#?


I Have a class and inside this class a string variable. I want to replace all the occurrences of specific words inside this variable with the List<string> of string.

using System;
using System.Collections.Generic;
public class HelloWorld
{
    List<string> lst = new List<string>();
    lst.Add("Sunil");
    lst.Add("Sunil123");
    lst.Add("Sunil@123");
    string smsTemplate = "Dear {#var#},You have successfully register to online system please login to system by below credentials,User Name : {#var#}   Password : {#var#}  SunSoft, DeshlahreMiniGraden";
    string searchStr = "{#var#}";
}

So the output of this "smsTemplate" variable should be replaced with the list of strings provided. For example "Sunil" should be placed at the position of first "{#var#}","Sunil123" should be replaced at the position of second "{#var#}" and so on.


Solution

  • You could do it in a quite straight-forward manner by splitting the smsTemplate on the searchStr and building a new string by appending the split parts from smsTemplate and each item in lst in an alternating manner. For instance:

    List<string> lst = new List<string>();
    
    lst.Add("Sunil");
    lst.Add("Sunil123");
    lst.Add("Sunil@123");
    
    string smsTemplate = "Dear {#var#},You have successfully register to online system please login to system by below credentials,User Name : {#var#}   Password : {#var#}  SunSoft, DeshlahreMiniGraden";
    string searchStr = "{#var#}";
    
    var templateParts = smsTemplate.Split(searchStr);
    
    // In case the {#var#} count in smsTemplate differs from the lst count
    var replacementCount = Math.Min(lst.Count, templateParts.Length - 1);
    
    var builder = new StringBuilder(templateParts[0]);
    
    for (var i = 0; i < replacementCount; i++)
    {
        builder.Append(lst[i]);
        builder.Append(templateParts[i + 1]);
    }
    
    var sms = builder.ToString();
    

    A fiddle is found here.