开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜