Variable String.Format length

北慕城南 提交于 2019-12-08 02:16:54

问题


I have the following code:

var str = "ABC";
var n = 7;
var output = String.Format("{0,n}", str);

This should output the string

"    ABC"

How should I change the line above?


回答1:


Format strings are just strings too - you can define the format separately:

int n = 3;
string format = string.Format("{{0,{0}}}", n);
//or more readable: string format = "{0," + n + "}";
var output = string.Format(format, str);

Edit:

After your update it looks like what you want can also be achieved by PadLeft():

var str = "ABC";
string output = str.PadLeft(7);



回答2:


Just write:

var lineLength = String.Format("{0," + n + "}", str);



回答3:


var s="Hello my friend";
string leftSpace = s.PadLeft(20,' '); //pad left with special character
string rightSpace = s.PadRight(20,' '); //pad right with special character


来源:https://stackoverflow.com/questions/9542994/variable-string-format-length

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!