Can maximum number of characters be defined in C# format strings like in C printf?

后端 未结 6 633
失恋的感觉
失恋的感觉 2020-12-10 01:42

Didn\'t find how to do that. What I found was more or less on the lines of this (http://blog.stevex.net/string-formatting-in-csharp/):

There really isn’t any formatt

6条回答
  •  青春惊慌失措
    2020-12-10 02:12

    This is not an answer on how to use string.format, but another way of shortening a string using extension methods. This way enables you to add the max length to the string directly, even without string.format.

    public static class ExtensionMethods
    {
        /// 
        ///  Shortens string to Max length
        /// 
        /// String to shortent
        /// shortened string
        public static string MaxLength(this string input, int length)
        {
            if (input == null) return null;
            return input.Substring(0, Math.Min(length, input.Length));
        }
    }
    

    sample usage:

    string Test = "1234567890";
    string.Format("Shortened String = {0}", Test.MaxLength(5));
    string.Format("Shortened String = {0}", Test.MaxLength(50));
    
    Output: 
    Shortened String = 12345
    Shortened String = 1234567890
    

提交回复
热议问题