问题描述
请问.NET的String.Format方法允许一个字符串放置在一个固定长度的字符串中的一个固定的位置。
Does the .NET String.Format method allow placement of a string at a fixed position within a fixed length string.
" String Goes Here"
" String Goes Here "
"String Goes Here "
这是如何使用.NET做?
How is this done using .NET?
修改 - 我试图格式/ PadLeft / PadRight死亡。他们不工作。我不知道为什么。最后我写我自己的函数来做到这一点。
Edit - I have tried Format/PadLeft/PadRight to death. They do not work. I don't know why. I ended up writing my own function to do this.
修改 - 我犯了一个错误,并使用一个冒号而不是在格式说明一个逗号。应该是{0,20}。
Edit - I made a mistake and used a colon instead of a comma in the format specifier. Should be "{0,20}".
感谢所有的优秀的和正确的答案。
Thanks for all of the excellent and correct answers.
推荐答案
这会给你正是你问的字符串:
This will give you exactly the strings that you asked for:
string s = "String goes here";
string line1 = String.Format("{0,27}", s);
string line2 = String.Format("{0,-27}", String.Format("{0," + ((27 + s.Length) / 2).ToString() + "}", s));
string line3 = String.Format("{0,-27}", s);
这篇关于.NET格式化字符串固定的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!