簡體   English   中英

將數字轉換為字母

[英]Convert number to alphabet letter

我想將一個數字轉換為其相應的字母。 例如:

1 = A
2 = B
3 = C

這可以在 javascript 中完成而無需手動創建數組嗎? 在 php 中有一個 range() 函數可以自動創建數組。 javascript中有類似的東西嗎?

是的,使用Number#toString(36)和一個調整。

 var value = 10; document.write((value + 9).toString(36).toUpperCase());

您可以使用String.fromCharCode(code)函數在沒有數組的情況下簡單地執行此操作,因為字母具有連續代碼。 例如: String.fromCharCode(1+64)給你'A', String.fromCharCode(2+64)給你'B',依此類推。

下面的代碼段將字母表中的字符變成數字系統

1 = A
2 = 乙
...
26 = Z
27 = AA
28 = AB
...
78 = BZ
79 = 加利福尼亞州
80 = CB

var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var result = ""
function printToLetter(number){
    var charIndex = number % alphabet.length
    var quotient = number/alphabet.length
    if(charIndex-1 == -1){
        charIndex = alphabet.length
        quotient--;
    }
    result =  alphabet.charAt(charIndex-1) + result;
    if(quotient>=1){
        printToLetter(parseInt(quotient));
    }else{
        console.log(result)
        result = ""
    }
}

我創建了這個函數來在打印時保存字符但不得不廢棄它,因為我不想處理可能最終形成的不正確的單詞

我構建了以下解決方案作為對@esantos 答案的增強。

第一個函數定義了一個有效的查找編碼字典。 在這里,我使用了英文字母表的所有 26 個字母,但以下也同樣適用: "ABCDEFG""ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789""GFEDCBA" 使用這些字典之一將導致將您的 base 10 數字轉換為具有適當編碼數字的基本dictionary.length數字。 唯一的限制是字典中的每個字符都必須是唯一的。

function getDictionary() {
    return validateDictionary("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

    function validateDictionary(dictionary) {
        for (let i = 0; i < dictionary.length; i++) {
            if(dictionary.indexOf(dictionary[i]) !== dictionary.lastIndexOf(dictionary[i])) {
                console.log('Error: The dictionary in use has at least one repeating symbol:', dictionary[i])
                return undefined
            }
        }
        return dictionary
    }
}

我們現在可以使用這個字典來編碼我們的基數為 10 的數字。

function numberToEncodedLetter(number) {
    //Takes any number and converts it into a base (dictionary length) letter combo. 0 corresponds to an empty string.
    //It converts any numerical entry into a positive integer.
    if (isNaN(number)) {return undefined}
    number = Math.abs(Math.floor(number))

    const dictionary = getDictionary()
    let index = number % dictionary.length
    let quotient = number / dictionary.length
    let result
    
    if (number <= dictionary.length) {return numToLetter(number)}  //Number is within single digit bounds of our encoding letter alphabet

    if (quotient >= 1) {
        //This number was bigger than our dictionary, recursively perform this function until we're done
        if (index === 0) {quotient--}   //Accounts for the edge case of the last letter in the dictionary string
        result = numberToEncodedLetter(quotient)
    }

    if (index === 0) {index = dictionary.length}   //Accounts for the edge case of the final letter; avoids getting an empty string
    
    return result + numToLetter(index)

    function numToLetter(number) {
        //Takes a letter between 0 and max letter length and returns the corresponding letter
        if (number > dictionary.length || number < 0) {return undefined}
        if (number === 0) {
            return ''
        } else {
            return dictionary.slice(number - 1, number)
        }
    }
}

一組編碼的字母很棒,但是如果我不能將它轉換回以 10 為基數的數字,那么它對計算機來說是無用的。

function encodedLetterToNumber(encoded) {
    //Takes any number encoded with the provided encode dictionary 

    const dictionary = getDictionary()
    let result = 0
    let index = 0

    for (let i = 1; i <= encoded.length; i++) {
        index = dictionary.search(encoded.slice(i - 1, i)) + 1
        if (index === 0) {return undefined} //Attempted to find a letter that wasn't encoded in the dictionary
        result = result + index * Math.pow(dictionary.length, (encoded.length - i))
    }

    return result
}

現在來測試一下:

console.log(numberToEncodedLetter(4))     //D
console.log(numberToEncodedLetter(52))    //AZ
console.log(encodedLetterToNumber("BZ"))  //78
console.log(encodedLetterToNumber("AAC")) //705

更新

您還可以使用此函數來獲取您擁有的短名稱格式並將其返回為基於索引的格式。

function shortNameToIndex(shortName) {
    //Takes the short name (e.g. F6, AA47) and converts to base indecies ({6, 6}, {27, 47})

    if (shortName.length < 2) {return undefined}    //Must be at least one letter and one number
    if (!isNaN(shortName.slice(0, 1))) {return undefined}  //If first character isn't a letter, it's incorrectly formatted

    let letterPart = ''
    let numberPart= ''
    let splitComplete = false
    let index = 1

    do {
        const character = shortName.slice(index - 1, index)
        if (!isNaN(character)) {splitComplete = true}
        if (splitComplete && isNaN(character)) {
            //More letters existed after the numbers. Invalid formatting.
            return undefined    
        } else if (splitComplete && !isNaN(character)) {
            //Number part
            numberPart = numberPart.concat(character)
        } else {
            //Letter part
            letterPart = letterPart.concat(character)
        }
        index++
    } while (index <= shortName.length)

    numberPart = parseInt(numberPart)
    letterPart = encodedLetterToNumber(letterPart)

    return {xIndex: numberPart, yIndex: letterPart}
}

只需將 letterIndex 從 0 (A) 增加到 25 (Z)

const letterIndex = 0
const letter = String.fromCharCode(letterIndex + 'A'.charCodeAt(0))

console.log(letter)

這可以幫助你

static readonly string[] Columns_Lettre = new[] { "A", "B", "C"};

public static string IndexToColumn(int index)
    {
        if (index <= 0)
            throw new IndexOutOfRangeException("index must be a positive number");

        if (index < 4)
            return Columns_Lettre[index - 1];
        else
            return index.ToString();
    }

暫無
暫無

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

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