Custom string formatter in C#

﹥>﹥吖頭↗ 提交于 2019-12-05 08:49:57

You can make a custom formatter, something like:

public class MyFormatter : IFormatProvider, ICustomFormatter
{
   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(ICustomFormatter))
         return this;
      else
         return null;
   }

   public string Format(string fmt, object arg, IFormatProvider formatProvider) 
   {
       if(arg == null) return string.Empty;

       if(fmt == "lcase")
           return arg.ToString().ToLower();
       else if(fmt == "ucase")
           return arg.ToString().ToUpper();
       else if(fmt == "nospace")
           return arg.ToString().Replace(" ", "");
       // Use this if you want to handle default formatting also
       else if (arg is IFormattable) 
           return ((IFormattable)arg).ToString(fmt, CultureInfo.CurrentCulture);
       return arg.ToString();
   }
}

Then use it like:

 string.Format(new MyFormatter(),
            "{0:lcase}, {0:ucase}, {0:nospace}", 
            "My Test String")

This should return:

my test string, MY TEST STRING, MyTestString

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!