簡體   English   中英

將數字轉換為字母串的最佳方法是什么?

[英]What is the best way of converting a number to a alphabet string?

在C#中將多位數轉換為字母串的最佳方法是什么?

例如,如果我有一個數字說,

int digits = 1234567890

我希望將其轉換為字符串

string alpha = "ABCDEFGHIJ"

這意味着1表示A,2表示B,依此類推。

像這樣的東西:

int input = 123450;
string output = "";

while (input > 0)
{
    int current = input % 10;
    input /= 10;

    if (current == 0)
        current = 10;

    output = (char)((char)'A' + (current - 1)) + output;
}

Console.WriteLine(output);

上面的代碼省去了通過數組或字典定義轉換列表的麻煩。 只需計算正確的Unicode代碼點即可完成轉換。

首先,0123將被解釋為123,因此前導0將被忽略。 這是一個可能的解決方案:

int i = 1230468;
StringBuilder res = new StringBuilder(i.ToString());

for (int j = 0; j < res.Length; j++)
   res[j] += (char)(17); // '0' is 48, 'A' is 65

Console.Out.WriteLine(res.ToString()); // result is BCDAEGI

沒有太多不同的符號可以替換,只需簡單的替換即可。

int digits = 0123456789;
string digitsAsString = digits.ToString("0000000000"); // Trick to preserve the 0.
string alpha = digitsAsString
    .Replace('0', 'A')
    .Replace('1', 'B')
    .Replace('2', 'C')
    .Replace('3', 'D')
    .Replace('4', 'E')
    .Replace('5', 'F')
    .Replace('6', 'G')
    .Replace('7', 'H')
    .Replace('8', 'I')
    .Replace('9', 'J');
Console.WriteLine(alpha);

注意這個指示

output = (char)((char)'A' + (current - 1)) + output;

在每次迭代時,它都會創建新對象。 必須使用StringBuilder完成字符串連接 ...

我必須對這篇文章的答案進行一般性的考慮。 開發人員不僅要注意優雅,算法效率,還要注意內存效率。

C#不是C o C ++而對象是壞動物:-)

制作一系列字符:

char alphabet = {'A','B','C' .... }

然后使用數字編號作為數組的索引:

digit = 14567
char[] digit_ar = new String(digit).ToCharArray();

foreach (char c in digit_ar)
{
    string s+=digit_ar[Convert.ToInt32(c)-Base];
}

Base是A char代碼

這是一個偽代碼,我沒有測試過!

它應該工作......

使用Dictionary類,看看這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM