代码之家  ›  专栏  ›  技术社区  ›  char m

C C格式字符串中最大的字符数是否可以像C PrimTF那样定义?

  •  12
  • char m  · 技术社区  · 14 年前

    没找到怎么做的。我发现多少有点像( http://blog.stevex.net/string-formatting-in-csharp/ ):

    字符串中除了对齐之外,实际上没有任何格式。对齐适用于字符串中打印的任何参数。格式调用。 样本生成

    String.Format(“->{1,10}<-”, “Hello”);  // gives "->     Hello<-" (left padded to 10)
    String.Format(“->{1,-10}<-”, “Hello”); // gives "->Hello     <-" (right padded to 10)
    
    5 回复  |  直到 9 年前
        1
  •  7
  •   Paolo Tedesco    14 年前

    您想要的不是“本机”支持的C字符串格式,因为 String.ToString string对象的方法只返回字符串本身。

    当你打电话

    string.Format("{0:xxx}",someobject);
    

    ToString(string format,IFormatProvider formatProvider) 方法被调用,其中“xxx”为 format 参数。

    如果您真的需要这样做,您可以使用任何建议的解决方法,或者创建自己的类来实现IFormattable接口。

        2
  •  5
  •   Andy    7 年前

    这不是关于如何使用string.format的答案,而是使用扩展方法缩短字符串的另一种方法。这样,即使没有string.format,也可以直接将最大长度添加到字符串中。

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

    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
    
        3
  •  1
  •   Doug Wiley    7 年前

    我编写了一个自定义格式化程序,它实现了一个用于设置最大宽度的“L”格式说明符。当我们需要控制格式化输出的大小时(比如当目标是数据库列或Dynamics CRM字段时),这非常有用。

    public class StringFormatEx : IFormatProvider, ICustomFormatter
    {
        /// <summary>
        /// ICustomFormatter member
        /// </summary>
        public string Format(string format, object argument, IFormatProvider formatProvider)
        {
            #region func-y town
            Func<string, object, string> handleOtherFormats = (f, a) => 
            {
                var result = String.Empty;
                if (a is IFormattable) { result = ((IFormattable)a).ToString(f, CultureInfo.CurrentCulture); }
                else if (a != null) { result = a.ToString(); }
                return result;
            };
            #endregion
    
            //reality check.
            if (format == null || argument == null) { return argument as string; }
    
            //perform default formatting if arg is not a string.
            if (argument.GetType() != typeof(string)) { return handleOtherFormats(format, argument); }
    
            //get the format specifier.
            var specifier = format.Substring(0, 1).ToUpper(CultureInfo.InvariantCulture);
    
            //perform extended formatting based on format specifier.
            switch(specifier)
            {
                case "L": 
                    return LengthFormatter(format, argument);
                default:
                    return handleOtherFormats(format, argument);
            }
        }
    
        /// <summary>
        /// IFormatProvider member
        /// </summary>
        public object GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter))
                return this;
            else
                return null;
        }
    
        /// <summary>
        /// Custom length formatter.
        /// </summary>
        private string LengthFormatter(string format, object argument)
        {
            //specifier requires length number.
            if (format.Length == 1)
            {
                throw new FormatException(String.Format("The format of '{0}' is invalid; length is in the form of Ln where n is the maximum length of the resultant string.", format));
            }
    
            //get the length from the format string.
            int length = int.MaxValue;
            int.TryParse(format.Substring(1, format.Length - 1), out length);
    
            //returned the argument with length applied.
            return argument.ToString().Substring(0, length);
        }
    }
    

    用法是

    var result = String.Format(
        new StringFormatEx(),
        "{0:L4} {1:L7}",
        "Stack",
        "Overflow");
    
    Assert.AreEqual("Stac Overflo", result);
    
        4
  •  0
  •   Ian Johnson    14 年前

    不能用参数而不是格式应用长度参数吗?

    String.Format(“->{0}<-”,toFormat.PadRight(10));//->您好<-

        5
  •  0
  •   Moo-Juice    14 年前

    为什么不使用Substr来限制字符串的长度呢?

    String s = "abcdefghijklmnopqrstuvwxyz";
    String.Format("Character limited: {0}", s.Substr(0, 10));
    
        6
  •  0
  •   john whitegun    5 年前

    您可能希望在将来的应用程序中使用此帮助器,它在给定的最大长度上限制字符串,并且如果它比给定的限制短,则还需要垫片。

    public static class StringHelper
    {
    
        public static string ToString(this string input , int maxLength , char paddingChar = ' ', bool isPaddingLeft = true)
        {
            if (string.IsNullOrEmpty(input))
                return new string('-', maxLength);
            else if (input.Length > maxLength)
                return input.Substring(0, maxLength);
            else
            {
                int padAmount = maxLength - input.Length;
                if (isPaddingLeft)
                    return input + new string(paddingChar, padAmount);
                else
                    return new string(paddingChar, padAmount) + input;
            }
        }
    }
    

    你可以把它当作:

     string inputStrShort = "testString";
     string inputStrLong = "mylongteststringexample";
     Console.WriteLine(inputStrShort.ToString(20, '*', true)); // Output : testString**********
     Console.WriteLine(inputStrLong.ToString(20, '*', true));  // Output : mylongteststringexam