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

时间:2018-02-25 04:17:46

标签: c#

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

因为汉字不同宽度我不能与string.format

对齐

示例:

numpy.var(img, axis=1)

有任何帮助吗?多种语言格式?

3 个答案:

答案 0 :(得分:2)

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

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

访问this link了解有效的演示。

答案 1 :(得分:0)

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

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("x   x", f).Width - g.MeasureString("x  x", 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");
    }
}

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

答案 2 :(得分:0)

确实是字体问题。我遇到了这个问题,我的 WPF 文本框输出看起来像这样

非收入服务费                        $0.0
折扣                     0          $0.0
退回项                   0          $0.0
更正合计                 0          $0.0
贷项合计                            $0.0
费用总计                           $42.6

正如 https://stackoverflow.com/a/48970839/15766965 中所建议的那样,选择中文符号与拉丁字符大小一致的字体可能会有所帮助。 (即中文符号所占用的宽度是拉丁字符所占用宽度的两倍或整数倍)。

这些字体对我有用

  1. SimSun
  2. SimSun-ExtB

现在,应该可以调整填充逻辑并获得所需的列宽。 在 Q 中,第一列的宽度是 40 个字符,所以如果我们有 4 个中文符号,那么所需的空格数是:

40 - (2)*4 = 32

(假设每个汉字的宽度是普通字符的两倍)

需要单独的逻辑来计算一个字符串中占据更多宽度的中文符号的总数。

相关问题