C#将数字更改为字符串中的小索引

时间:2012-01-21 21:31:22

标签: c# .net winforms subscript

我有字符串“H20”(水的化学式)。我想改变它,以便字符串中的所有数字都很小(数字2将是字母H旁边的小索引)。我怎么能这样做?

2 个答案:

答案 0 :(得分:4)

假设您有显示下标unicode字符的方法,您可以轻松编写自己的下标方法进行下标:

public static string Subscript(this string normal)
{
    if(normal == null) return normal;

    var res = new StringBuilder();
    foreach(var c in normal)
    {
        char c1 = c;

        // I'm not quite sure if char.IsDigit(c) returns true for, for example, '³',
        // so I'm using the safe approach here
        if (c >= '0' && c <= '9')
        {
            // 0x208x is the unicode offset of the subscripted number characters
            c1 = (char)(c - '0' + 0x2080);
        }
        res.Append(c1);
    }

    return res.ToString();
}

答案 1 :(得分:3)

正如评论中指出的那样,您通常应该使用一些演示技术来实现这种格式化。例如,在HTML中,您可以通过以下方式显示文本:

<span>H<sub>2</sub>O</span>

但是,Unicode为您可以利用的十六进制字符分配superscripts and subscripts block。由于.NET本身支持Unicode,包括字符串文字,因此您可以直接使用所需的字符:

text = text.Replace("H2O", "H₂O");

注意:使用Unicode下标字符可以保证您的H₂O字符串可以在任何支持Unicode的应用程序中正确呈现,无论其格式化技术如何(HTML,RTF,PDF,XPS)等等。)

下面的屏幕截图显示了字符串在Windows窗体下的TextBox中的呈现方式。为了提高易读性,字体已更改为Cambria,11.25pt。

H₂O as rendered in a TextBox under Windows Forms

修改:如果您想将所有数字(不只是2)转换为),您可以使用@ Tobias的代码。这是对它的正则表达式的改编。我已经包含了一个lookbehind,因为我假设所有要下标的数字必须以字母开头。

text = Regex.Replace(text, @"(?<=[A-Za-z])\d", 
    match => ((char)(match.Value[0] - '0' + '₀')).ToString());

上面会转换像

这样的字符串
CF3CH2Cl + Br2 → CF3CHBrCl + HBr

CF₃CH₂Cl + Br₂ → CF₃CHBrCl + HBr