多种语言的C#字符串格式

我正在尝试格式化英文字符和汉字左右对齐

因为汉字是不同的宽度我不能与string.format对齐

例:

String.Format("{0,-40}{1,8}", "some string", $20.00); String.Format("{0,-40}{1,8}", "些字符串些字符串些字符串些字符串", $20.00); String.Format("{0,-40}{1,8}", "些", $20.00); String.Format("{0,-40}{1,8}", "a", $20.00); |------------------------------total char 48 char always-------------| -------------name 40 char maximum ---------- | -price 8 char always- some string $20.00 些字符串些字符串些字符串些字符串 $15.00 些 $8.00 a $100.00 

有帮助吗? 多语言格式?

您应该使用表格来处理此问题,而不是使用复合格式来抵消字符串。 它们的主要目的是在具有不匹配长度的字符串列之间创建均匀的间距。 方法如下:

 String s1 = String.Format("{0}\t\t\t\t{1}", "some string", "$20.00"); String s2 = String.Format("{0}\t\t\t\t{1}", "一些字符串", "$20.00"); String s3 = String.Format("{0}\t\t\t\t{1}", "some 一些字符串", "$20.00"); 

上面例子的输出是:

 some string $20.00一些字符串 $20.00 some 一些字符串 $20.00 

访问此链接以获取有效的演示。

我认为格式取决于使用的字体。 但是如果您知道字体,可以直接测量它,例如:

 public string padString(string s, Graphics g, Font f, float desiredWidth, float spaceWidth) { float orig = g.MeasureString(s, f).Width; int spaceCount = (int)Math.Max(0, (desiredWidth - orig) / spaceWidth); return s + new string(' ', spaceCount) + '\t'; } private void button1_Click(object sender, EventArgs e) { using (Graphics g = CreateGraphics()) { Font f = textBox1.Font; float tabWidth = g.MeasureString("x\t\t\tx", f).Width - g.MeasureString("x\t\tx", f).Width; float spaceWidth = g.MeasureString("xx", f).Width - g.MeasureString("xx", f).Width; float dw = tabWidth * 5.5f; // half of the tab is on purpose String s1 = String.Format("{0}{1,8}", padString("some string", g, f, dw, spaceWidth), "$20.00"); String s2 = String.Format("{0}{1,8}", padString("些字符串些字符串些字符串些字符串", g, f, dw, spaceWidth), "$20.00"); String s3 = String.Format("{0}{1,8}", padString("些", g, f, dw, spaceWidth), "$20.00"); String s4 = String.Format("{0}{1,8}", padString("a", g, f, dw, spaceWidth), "$20.00"); textBox1.AppendText(s1 + "\n"); textBox1.AppendText(s2 + "\n"); textBox1.AppendText(s3 + "\n"); textBox1.AppendText(s4 + "\n"); } } 

或者您可以选择更可预测的字体(如中文字符是英文宽度的两倍)并直接计算宽度。