How to provide custom string placeholder for string format

后端 未结 8 2132
借酒劲吻你
借酒劲吻你 2020-12-24 07:15

I have a string

string str =\"Enter {0} patient name\";

I am using string.format to format it.

String.Format(str, \"Hello\         


        
8条回答
  •  失恋的感觉
    2020-12-24 07:47

    You can also use the example from Marc Gravell and Extend the String class object:

    public static class StringExtension
    {
        static readonly Regex re = new Regex(@"\{([^\}]+)\}", RegexOptions.Compiled);
        public static string FormatPlaceholder(this string str, Dictionary fields)
        {
            if (fields == null)
                return str;
    
            return re.Replace(str, delegate(Match match)
            {
                return fields[match.Groups[1].Value];
            });
    
        }
    }
    

    Example usage:

    String str = "I bought a {color} car";
    Dictionary fields = new Dictionary();
    fields.Add("color", "blue");
    
    str.FormatPlaceholder(fields));
    

提交回复
热议问题