将指数数字字符串表示拆分为幂和指数 [英] Split exponential number string representation into power and exponent
问题描述
我有来自资源的指数形式的字符串,如下所示:2⁴
.我想知道是否有办法将其拆分为:
I have strings which come from resources in exponential form like the following: 2⁴
. I was wondering if there is a way to split this into:
var base = 2; //or even "2", this is also helpful since it can be parsed
和
var exponent = 4;
我搜索了互联网和 msdn 标准数字也格式化字符串,但我无法找到解决这种情况的方法.
I have searched the internet and msdn Standard Numeric Format Strings also, but I was unable to find the solve for this case.
推荐答案
您可以添加数字到上标数字之间的映射,然后从源中选择所有数字(这将是 base
)和所有其他 - 指数
You can add mapping between digits to superscript digits, then select all digits from source (this will be the base
) and all the others - the exponent
const string superscriptDigits = "⁰¹²³⁴⁵⁶⁷⁸⁹";
var digitToSuperscriptMapping = superscriptDigits.Select((c, i) => new { c, i })
.ToDictionary(item => item.c, item => item.i.ToString());
const string source = "23⁴⁴";
var baseString = new string(source.TakeWhile(char.IsDigit).ToArray());
var exponentString = string.Concat(source.SkipWhile(char.IsDigit).Select(c => digitToSuperscriptMapping[c]));
现在您可以将 base
和 exponent
转换为 int
.此外,您还需要在执行转换代码之前验证输入.
Now you can convert base
and exponent
to int
.
Also you'll need to validate input before executing conversion code.
甚至没有映射:
var baseString = new string(source.TakeWhile(char.IsDigit).ToArray());
var exponentString = string.Concat(source.SkipWhile(char.IsDigit).Select(c => char.GetNumericValue(c).ToString()));
这篇关于将指数数字字符串表示拆分为幂和指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!