将一个字符串与另一个字符串对齐
你的问题有点不清楚(例子有助于澄清)。此外,你还没有完全指定你期望的输出(当第二个字符串不能居中在第一个字符串上,因为它太长了吗?)你会发现完全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
(将多余的 '!' 是为了让你能看到的填充。)
你可以很容易地修改这个在存在奇数额外空间的情况下,额外空间根据您的需要左右移动(目前它在右侧)(重构接受参数!)。
这只适用于非比例(固定宽度)字体。一般来说,对于所有字体......如果两个字符串不对称地填充了不同的宽度字符(第一个字符串具有宽字符的优先级(Ws,Ms,Hs等),并且第二个字符串具有窄字符的优势,如i,l ,标点符号等),那么这将不起作用。 – 2009-11-25 20:00:19
他说中心字符串,而不是字符串(文本)的中心视觉表示。 (我同意这样一个明显的陈述,即他的要求是模糊不清的。) – jason 2009-11-25 20:43:36
您的问题不清楚。也许.PadLeft
和.PadRight
方法会帮助你。
最简单的解决方案是将字符串放入水平对齐的文本框中,并将它们的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;
这会将字符串(文本)的可视表示集中在一个窗口中,但不一定是他试图解决的问题。 – jason 2009-11-25 20:43:06
这是控制台输出,WPF,还是什么? – HackedByChinese 2009-11-25 19:22:32
您是在谈论ASP.NET,控制台还是Web窗体? – 2009-11-25 19:22:37
什么......那个?是吧? – 2009-11-25 19:22:38