Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

unicode - Convert a string/integer to superscript in C#

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

"01234"

to:

"u2070u00B9u00B2u00B3u2074"

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = 
    "u2070u00b9u00b2u00b3u2074u2075u2076u2077u2078u2079";

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...