C# Create a subscript in a string

Leon Bohmann picture Leon Bohmann · Aug 6, 2015 · Viewed 8.4k times · Source

Currently I am trying to fix some formatting in my application. I am trying to subscript a string and append it to a normal string- the same way you can do it in MS word. I already tried this (as supposed here and here):

string temp = "NormalText";
foreach( char t in "SubscriptedText".ToCharArray())
    temp += "\x208" + t;

MessageBox.Show(temp);

Output: NormalTextȈSȈuȈbȈsȈcȈrȈiȈpȈtȈeȈdȈTȈeȈxȈt

But, as I noted afterwards it is the font who has to support the unicode definitions. And on the internet there doesn't seem to be a font who supports all letters in supscripted format.

So, is there a way to format my text in order to subscript the second half of it? Maybe a simple function I am missing? Or is this just not possible and I have to align my subscripted text on my own?

EDIT Also tried this:

string temp = "NormalText";
foreach( char t in "SubscriptedText".ToCharArray())
    temp += "\x208" + (int)t;

MessageBox.Show(temp);

But (of course) this didn't work out at all. I've got my output looking like this:

NormalTextȈ84Ȉ105Ȉ101Ȉ102Ȉ101Ȉ114Ȉ84Ȉ101Ȉ120Ȉ11

Answer

Alexander Pavlenko picture Alexander Pavlenko · Aug 6, 2015

First of all there are limeted number of symbols which can be used for subscription. There are these symbols:

1 - '\u2081'
2-  '\u2082'
3-  '\u2083'
...
9 - '\u2089'
+ - '\u208A'
- - '\u208B'
= - '\u208C'
( - '\u208D'
) - '\u208E'

That's all. So you can't subscript the string like "SubscriptedText".

If you want convert to subscription some digit or allowed symbol you can try the following way:

void ShowSubText()
    {
        String inputString = "NormalText";
        var nonDigitSymbolsTable = new Dictionary<char, char>();
        nonDigitSymbolsTable.Add('+', 'A');
        nonDigitSymbolsTable.Add('-', 'B');
        nonDigitSymbolsTable.Add('=', 'C');
        nonDigitSymbolsTable.Add('(', 'D');
        nonDigitSymbolsTable.Add(')', 'E');
        StringBuilder temp = new StringBuilder();
        int checkToDigit = 0;
        foreach (char t in "1234567890+-=()".ToCharArray())
        {
            if (int.TryParse(t.ToString(), out checkToDigit))
                temp.Append("\\u208" + t);
            else
                temp.Append("\\u208" + nonDigitSymbolsTable[t]);
        }

        MessageBox.Show(inputString + GetStringFromUnicodeSymbols(temp.ToString()));
    }
    string GetStringFromUnicodeSymbols(string unicodeString)
    {
        var stringBuilder = new StringBuilder();
        foreach (Match match in Regex.Matches(unicodeString, @"\\u(?<Value>[a-zA-Z0-9]{4})"))
        {
            stringBuilder.AppendFormat(@"{0}",
                                       (Char)int.Parse(match.Groups["Value"].Value,System.Globalization.NumberStyles.HexNumber));
        }

        return stringBuilder.ToString();
    }