可以在C#格式字符串中定义最大字符数,例如C printf吗?

没找到怎么做。 我发现的或多或少就是这个( http://blog.stevex.net/string-formatting-in-csharp/ ):

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

String.Format(“->{1,10}     Hello{1,-10}Hello     <-" (right padded to 10) 

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

你打电话的时候

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

如果someobject实现IFormattable接口,则调用重载ToString(字符串格式,IFormatProvider formatProvider)方法,并将“xxx”作为format参数。

因此,最多,这不是.NET字符串格式设计中的缺陷,而是字符串类中缺少function。

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

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

 public class StringFormatEx : IFormatProvider, ICustomFormatter { ///  /// ICustomFormatter member ///  public string Format(string format, object argument, IFormatProvider formatProvider) { #region func-y town Func 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); } } ///  /// IFormatProvider member ///  public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) return this; else return null; } ///  /// Custom length formatter. ///  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); 

你不能只使用参数而不是格式来应用长度参数吗?

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

或者编写自己的格式化程序以允许您执行此操作?

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

 String s = "abcdefghijklmnopqrstuvwxyz"; String.Format("Character limited: {0}", s.Substr(0, 10)); 

这不是如何使用string.format的答案,而是使用扩展方法缩短字符串的另一种方法。 这种方式使您可以直接向字符串添加最大长度,即使没有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)); } } 

样品用量:

 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