我想通过确保显示的第二个字符串显示在第一个字符串输出的中心,将字符串居中于另一个字符串。我如何在C#中这样做呢。提前致谢
答案 0 :(得分:5)
您的问题有点不清楚(示例有助于澄清)。此外,你没有完全指定你期望的输出(当第二个字符串不能在第一个字符串中居时我们抛出因为它太长了吗?)你会发现完全specifying your requirements会帮助你写你的代码!也就是说,我认为你正在寻找类似的东西。
使用
public static string CenterWithRespectTo(string s, string against) {
if(s == null) {
throw new ArgumentNullException("s");
}
if(against == null) {
throw new AgrumentNullException("against");
}
if (s.Length > against.Length) {
throw new InvalidOperationException();
}
int halfSpace = (against.Length - s.Length) / 2;
return s.PadLeft(halfSpace + s.Length).PadRight(against.Length);
}
这样
string s = "Hello";
string against = "My name is Slim Shady";
Console.WriteLine(CenterWithRespectTo(s, against) + "!");
Console.WriteLine(against);
产生
Hello !
My name is Slim Shady
(无关的'!'是这样你可以看到填充。)
您可以轻松修改此项,以便在存在奇数额外空间的情况下,根据您的需要(重构接受参数!),额外空间位于左侧或右侧(当前位于右侧)。
答案 1 :(得分:3)
最简单的解决方案是将字符串放入水平对齐的文本框中,并将它们的textalignment属性设置为“居中”。
否则,你需要测量字符串的像素长度,当用指定的字体绘制时...然后将较短的字符串的起始x坐标偏移两个长度之差的一半......
string s1 = "MyFirstString";
string s2 = "Another different string";
Font f1 = new Font("Arial", 12f);
Font f2 = new Font("Times New Roman", 14f);
Graphics g = CreateGraphics();
SizeF sizeString1 = g.MeasureString(s1, f1),
sizeString2 = g.MeasureString(s2, f2);
float offset = sizeString2.Width - sizeString1.Width / 2;
// Then offset (to the Left) the position of the label
// containing the second string by this offset value...
// offset to the left, because If the second string is longer,
// offset will be positive.
Label lbl1 = // Label control for string 1,
lbl2 = // Label control for string 2;
lbl1.Text = s1;
lbl1.Font = f1;
lbl1.Left = //Some value;
lbl2.Text = s2;
lbl2.Font = f2;
lbl2.Left == lbl1.Left - offset;
答案 2 :(得分:0)
你的问题不清楚。也许.PadLeft
和.PadRight
方法会对您有所帮助。