Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string/integer to superscript in C#

Tags:

c#

unicode

Is there a built in .NET function or an easy way to convert from:

"01234"

to:

"\u2070\u00B9\u00B2\u00B3\u2074"

Note that superscript 1, 2 and 3 are not in the range \u2070-\u209F but \u0080-\u00FF.

like image 887
Dave Hillier Avatar asked Jun 21 '11 20:06

Dave Hillier


1 Answers

EDIT: I hadn't noticed that the superscript characters weren't as simple as \u2070-\u2079. You probably want to set up a mapping between characters. If you only need digits, you could just index into a string fairly easily:

const string SuperscriptDigits = 
    "\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079";

Then using LINQ:

string superscript = new string(text.Select(x => SuperscriptDigits[x - '0'])
                                    .ToArray());

Or without:

char[] chars = text.ToArray();
for (int i = 0; i < chars.Length; i++)
{
    chars[i] = SuperscriptDigits[chars[i] - '0'];
}
string superscript = new string(chars);
like image 97
Jon Skeet Avatar answered Sep 24 '22 22:09

Jon Skeet