Centering a String against another string
I would like to center a string against another string by making sure the second string displayed appears centered to t开发者_Go百科he first string output. How do I go about doing this in C# please. Thanks in advance
Your question is somewhat unclear (examples help clarify). Further, you haven't fully specified the output that your expecting (do we throw when the second string can't be centered on the first string because it's too long?) You'll find that fully specifying your requirements will help you write your code! That said, I think you're looking for something like that following.
Use
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);
}
so that
string s = "Hello";
string against = "My name is Slim Shady";
Console.WriteLine(CenterWithRespectTo(s, against) + "!");
Console.WriteLine(against);
produces
Hello !
My name is Slim Shady
(The extraneous '!' is so that you can see the padding.)
You can easily modify this so that in cases where there is an odd amount of additional space the extra space goes on the left or right (currently it goes on the right) according to your needs (refactor accepting a parameter!).
The simplest solution is to just put the strings into horizontally aligned text boxes, and set the textalignment property for both of them to "centered".
Otherwise, You need to measure the pixel length of the string, when drawn in a specified font... Then offset the shorter string's start x-coordinate by half the difference between the two lengths...
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;
Your question is unclear. Perhaps the .PadLeft
and .PadRight
methods would help you.
精彩评论