C# string format flag or modifier to lowercase param

前端 未结 2 758
情深已故
情深已故 2020-12-15 15:09

Is it possible to specify some kind of flag or modifier on a string format param to make it lower case or upper case?

Example of what I want:

String.         


        
相关标签:
2条回答
  • 2020-12-15 16:09

    There's only padding and allignment formating... So the easy way is like you said, use "John".ToUpper() or "John".ToLower().

    Another solution could be create a custom IFormatProvider, to provide the string format you want.

    This is how will look the IFormatProvider and the string.Format call.

    public class CustomStringFormat : IFormatProvider, ICustomFormatter
    {
        public object GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter))
                return this;
            else
                return null;
    
        }
    
        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            string result = arg.ToString();
    
            switch (format.ToUpper())
            {
                case "U": return result.ToUpper();
                case "L": return result.ToLower();
                //more custom formats
                default: return result;
            }
        }
    }
    

    And the call will look like:

    String.Format(new CustomStringFormat(), "Hi {0:U}", "John");
    
    0 讨论(0)
  • 2020-12-15 16:10

    In short, no; AFAIK you'd have to fix the source values, or use your own replacement to string.Format. Note that if you are passing in a custom culture (to string.Format) you may want to use culture.TextInfo.ToLower(s), rather than just s.ToLower().

    0 讨论(0)
提交回复
热议问题