我有以下代码:
var str = "ABC";
var n = 7;
var output = String.Format("{0,n}", str);
这应输出字符串
" ABC"
我应该如何更改上面的一行?
答案 0 :(得分:8)
格式字符串也只是字符串 - 您可以单独定义格式:
int n = 3;
string format = string.Format("{{0,{0}}}", n);
//or more readable: string format = "{0," + n + "}";
var output = string.Format(format, str);
编辑:
更新后,看起来您想要的内容也可以通过PadLeft()
:
var str = "ABC";
string output = str.PadLeft(7);
答案 1 :(得分:6)
只需写下:
var lineLength = String.Format("{0," + n + "}", str);
答案 2 :(得分:1)
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