You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中用string类型的List依次替换字符串中的指定占位符?

解决方案

要实现用列表元素依次替换模板中对应位置占位符的需求,不能直接用string.Replace()(它会把所有匹配项替换为同一个值),我们需要逐个定位并替换每个占位符实例,对应列表中的元素。以下是两种可行的实现方式:

方法一:使用String.Replace的重载版本

利用string.Replace(oldValue, newValue, count)重载方法,通过指定count=1每次只替换第一个匹配的占位符,依次遍历列表元素完成替换:

using System;
using System.Collections.Generic;

public class HelloWorld
{
    public static void Main()
    {
        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#}";
        
        string result = smsTemplate;
        int currentIndex = 0;
        
        // 循环替换每个占位符,直到替换完所有占位符或列表元素用尽
        while (result.Contains(searchStr) && currentIndex < lst.Count)
        {
            // 仅替换第一个匹配的占位符
            result = result.Replace(searchStr, lst[currentIndex], 1);
            currentIndex++;
        }
        
        Console.WriteLine(result);
    }
}

方法二:使用正则表达式的MatchEvaluator

适合更复杂的占位符场景,通过正则匹配每个占位符,用委托动态返回列表中的对应元素:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class HelloWorld
{
    public static void Main()
    {
        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#}";
        
        int elementIndex = 0;
        // 用正则转义处理占位符中的特殊字符,避免正则语法冲突
        string result = Regex.Replace(smsTemplate, Regex.Escape(searchStr), match => 
        {
            // 元素未用尽时返回对应元素,否则保留原占位符
            return elementIndex < lst.Count ? lst[elementIndex++] : match.Value;
        });
        
        Console.WriteLine(result);
    }
}

关键说明

  • 两种方式都能保证占位符和列表元素按顺序一一对应替换
  • 循环/委托中加入了元素数量判断,避免出现索引越界的问题
  • 正则方式的Regex.Escape用于转义占位符中的{、}等正则特殊字符,确保匹配准确

内容的提问来源于stack exchange,提问作者HEARTBEAT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 04:16:20