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

cha*_*r m 15 c# string string-formatting

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

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

String.Format(“->{1,10}<-”, “Hello”);  // gives "->     Hello<-" (left padded to 10)
String.Format(“->{1,-10}<-”, “Hello”); // gives "->Hello     <-" (right padded to 10)
Run Code Online (Sandbox Code Playgroud)

Pao*_*sco 7

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

你打电话的时候

string.Format("{0:xxx}",someobject);
Run Code Online (Sandbox Code Playgroud)

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

所以,最多,这不是.NET字符串格式设计中的缺陷,而是字符串类中缺少功能.

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


And*_*ndy 6

这不是关于如何使用 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

示例用法:

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
Run Code Online (Sandbox Code Playgroud)