Csharp/C#教程:多种语言的C#字符串格式分享


多种语言的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}tttt{1}", "some string", "$20.00"); String s2 = String.Format("{0}tttt{1}", "一些字符串", "$20.00"); String s3 = String.Format("{0}tttt{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("xtttx", f).Width - g.MeasureString("xttx", 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"); } } 

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

上述就是C#学习教程:多种语言的C#字符串格式分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1002907.html

(0)
上一篇 2021年12月27日
下一篇 2021年12月27日

精彩推荐