I have a problem regarding subscript characters in a string. Lets say i have the following string: O₂.
I want all subscribt characters of that string to be normal so the string will look like: O2.(and not O₂)
I am not sure how to do that i C#.
I have a problem regarding subscript characters in a string. Lets say i have the following string: O₂.
I want all subscribt characters of that string to be normal so the string will look like: O2.(and not O₂)
I am not sure how to do that i C#.
There is a general "decomposition" of all superscript and subscript characters in .NET, as described here: How to convert super- or subscript to normal text in C#.
However, if you want to do stuff manually, and if you want just the numbers 0-9 in subscript, they can be found at U+2080 - U+2089 (http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts).
So, you could use the C# string representation of unicode characters, \uXXXX
, and the int value of '0'
to help you.
The difference in character "numeric" values of the subscript of a number and the number in plain writing, would be:
(int) '\u2080' - (int) '0'
Putting it together, the following will probably explain it better:
using System.IO; using System;
class Program
{
static void Main()
{
var subscriptValue = (int) '\u2080';
var normalValue = (int) '0';
var diff = subscriptValue - normalValue;
Console.WriteLine("subscript value: {0}, normal value: {1}, difference: {2} ",
subscriptValue, normalValue, diff);
for (var i = normalValue; i <= (normalValue + 9); i++) {
char normal = (char) i;
char subscript = (char) (i + diff);
Console.WriteLine("Normal: {0}, subscript: {1}", normal, subscript);
}
}
}
If you want to convert standard unicode subscript block ([0x2080..0x209F] symbols) you may use this code:
http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts
/// <summary>
/// From subscript (standard subscript block [0x2080..0x209F] only) to normal
/// </summary>
public static String FromSubscript(String value) {
if (String.IsNullOrEmpty(value))
return value;
Char[] Symbols = new Char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '=', '(', ')', '?', // <- '?' unknown/not standard symbols
'a', 'e', 'o', 'x', '\u0259', 'h', 'k', 'l', 'm', 'n', 'p', 's', 't', '?', '?', '?' }; // <- u0259 - small latin shwa
StringBuilder result = new StringBuilder(value.Length);
foreach (Char ch in value) {
int v = (int) ch;
if ((v >= 0x2080) && (v <= 0x209F))
result.Append(Symbols[v - 0x2080]);
else
result.Append(ch);
}
return result.ToString();
}
...
String test = "O₂";
Debug.Assert(String.Equals(FromSubscript(test), "O2", StringComparison.Ordinal));