2016-07-07 20 views

回答

3

可以位數之間上標數字添加映射,然後選擇來自源的所有數字(這將是base)以及所有其他數字 - 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])); 

現在您可以將baseexponent轉換爲int。 您還需要在執行轉換代碼之前驗證輸入。


甚至沒有映射:

var baseString = new string(source.TakeWhile(char.IsDigit).ToArray()); 
var exponentString = string.Concat(source.SkipWhile(char.IsDigit).Select(c => char.GetNumericValue(c).ToString())); 
+0

我會,因爲它看起來像最乾淨的解決方案標誌着這是回答我案件。謝謝! – meJustAndrew

+0

@meJustAndrew這是沮喪的第一個回答,然後被複制切割與一些額外的鐘聲和哨子......並被忽略:( – sam

+0

@sam我知道你說什麼,昨天發生在我身上,我很抱歉,但這是最乾淨的解決方案,它是問題的答案。爲了改善您的答案以及如何贏得聲譽,請記住,在您回答之後,您可以繼續進行編輯,直到它達到最佳效果。再次,我爲此感到抱歉! – meJustAndrew

1

指數格式化的方式稱爲英文上標。 如果您使用該關鍵字進行搜索,可以找到許多與此相關的問題。

位數標Unicode中映射爲:

0 -> \u2070 
1 -> \u00b9 
2 -> \u00b2 
3 -> \u00b3 
4 -> \u2074 
5 -> \u2075 
6 -> \u2076 
7 -> \u2077 
8 -> \u2078 
9 -> \u2079 

你可以搜索你的字符串值:

Lis<char> superscriptDigits = new List<char>(){ 
    '\u2070', \u00b9', \u00b2', \u00b3', \u2074', 
\u2075', \u2076', \u2077', \u2078', \u2079"}; 

//the rest of the string is the expontent. Join remaining chars. 
str.SkipWhile(ch => !superscriptDigits.Contains(ch)); 

你的想法

0

您可以使用一個簡單的正則表達式(如果你的源很乾淨):

string value = "2⁴⁴"; 
string regex = @"(?<base>\d+)(?<exp>.*)"; 
var matches = Regex.Matches(value, regex); 

int b; 
int exp = 0; 

int.TryParse(matches[0].Groups["base"].Value, out b); 

foreach (char c in matches[0].Groups["exp"].Value) 
{ 
    exp = exp * 10 + expToInt(c.ToString()); 
} 

Console.Out.WriteLine("base is : {0}, exponent is {1}", b, exp); 

而且expToInt(基於Unicode subscripts and superscripts):

public static int expToInt(string c) 
{ 
    switch (c) 
    { 
     case "\u2070": 
      return 0; 
     case "\u00b9": 
      return 1; 
     case "\u00b2": 
      return 2; 
     case "\u00b3": 
      return 3; 
     case "\u2074": 
      return 4; 
     case "\u2075": 
      return 5; 
     case "\u2076": 
      return 6; 
     case "\u2077": 
      return 7; 
     case "\u2078": 
      return 8; 
     case "\u2079": 
      return 9; 
     default: 
      throw new ArgumentOutOfRangeException(); 
    } 
} 

這將輸出:

鹼是2,exp爲44

2

您可以String.Normalize一起使用正則表達式:

var value = "42⁴³"; 
var match = Regex.Match(value, @"(?<base>\d+)(?<exponent>[⁰¹²³⁴-⁹]+)"); 

var @base = int.Parse(match.Groups["base"].Value); 
var exponent = int.Parse(match.Groups["exponent"].Value.Normalize(NormalizationForm.FormKD)); 

Console.WriteLine($"base: {@base}, exponent: {exponent}"); 
相關問題