开发者

string.Format(): Format string by taking the width at run time C#.net 2.0

开发者 https://www.devze.com 2023-02-16 03:49 出处:网络
In normal string form开发者_JAVA百科at we would write like this: string formattedString = string.Format(\"{0, -30}\", someData.ToString());

In normal string form开发者_JAVA百科at we would write like this:

string formattedString = string.Format("{0, -30}", someData.ToString());

It formats the string 30 characters left aligned.

I wish to format strings of different varying widths and this width would be specified at run time. In above example I would pass width (30, 50, 60, etc.,) as parameter.

Pls help me to acheive this.


String formattedString = 
  String.Format("{0, -" + someData.ToString.Count() + "}", someData.ToString());

Without having to call someData.ToString() twice as it could be expensive.

String someDataString = someDate.ToString();
String formatteString = 
  String.Format("{0, -" + someDataString.Count() + "}", someDataString);


int alignment = 30;
string format = "{0, -" + alignment + "}";
string formattedString = String.Format(format, someData);

You don't need the ToString in many places. It's called by the String.Format and similar methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号