C# 将一根绳子与另一根绳子对中

C# 将一根绳子与另一根绳子对中,c#,C#,我希望通过确保显示的第二个字符串与第一个字符串输出居中,从而将一个字符串与另一个字符串居中。请问我该如何用C#来做这件事。提前感谢您的问题不清楚。也许.PadLeft和.PadRight方法会对您有所帮助。您的问题有些不清楚(示例有助于澄清)。此外,您还没有完全指定期望的输出(当第二个字符串不能集中在第一个字符串上时,因为它太长,我们会抛出吗?)您会发现,完全指定将帮助您编写代码!也就是说,我认为你在寻找类似的东西 使用 所以 string s = "Hello"; string against

我希望通过确保显示的第二个字符串与第一个字符串输出居中,从而将一个字符串与另一个字符串居中。请问我该如何用C#来做这件事。提前感谢

您的问题不清楚。也许
.PadLeft
.PadRight
方法会对您有所帮助。

您的问题有些不清楚(示例有助于澄清)。此外,您还没有完全指定期望的输出(当第二个字符串不能集中在第一个字符串上时,因为它太长,我们会抛出吗?)您会发现,完全指定将帮助您编写代码!也就是说,我认为你在寻找类似的东西

使用

所以

string s = "Hello";
string against = "My name is Slim Shady";
Console.WriteLine(CenterWithRespectTo(s, against) + "!");
Console.WriteLine(against);
产生

        Hello        !  
My name is Slim Shady
(多余的“!”是为了让您可以看到填充物。)


您可以很容易地对此进行修改,以便在存在奇数个额外空间的情况下,根据您的需要(重构接受参数!)将额外空间放在左侧或右侧(目前位于右侧)。

最简单的解决方案是将字符串放入水平对齐的文本框中,并将两者的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;

这是控制台输出、WPF还是什么?你说的是ASP.NET、控制台还是Web表单?而且,我认为这是不可能的。如果第一个字符串较短,而第二个字符串明显较长,则无法将其居中,因为第一个字符串是需要更改的字符串。对于各种类型的输出,您已经获得了一些很好的答案,但问题不清楚,也不是很有用。最好对输入做出反应,并澄清您需要什么;字符或像素。这仅适用于非比例(固定宽度)字体。不适用于所有字体。。。如果两个字符串以不对称的方式填充不同宽度的字符(第一个字符串以宽字符(Ws、Ms、Hs等)为主,第二个字符串以窄字符(如i、l、标点符号等)为主),那么这将不起作用。他说,中间字符串,而不是字符串(文本)的中心视觉表示。(我同意他的要求含糊不清的说法。)这将使字符串(文本)的视觉表现集中在窗口中,但不一定是他试图解决的问题。
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;