登录
首页 >  Golang >  Go问答

将列表示法和索引互相转换

来源:stackoverflow

时间:2024-02-15 23:03:25 303浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《将列表示法和索引互相转换》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

如何将索引(即 53)转换为列引用(即 GoLang 中的 BA)?下表显示了列和索引的双向预期输出。

即如果你输入703,你会得到AAA。如果您输入YOU,您将得到17311


正确答案


这是一个需要解决的有趣问题。该解决方案涉及2个功能:

indextocolumn(int) (string, error) 会将索引转换为 a1 表示法。例如703aaa

columntoindex(string) (int, error) 会将 a1 表示法转换为索引。例如ba53

这是代码:

// indexToColumn takes in an index value & converts it to A1 Notation
// Index 1 is Column A
// E.g. 3 == C, 29 == AC, 731 == ABC
func indexToColumn(index int) (string, error) {

    // Validate index size
    maxIndex := 18278
    if index > maxIndex {
        return "", web.Errorf("index cannot be greater than %v (column ZZZ)", maxIndex)
    }

    // Get column from index
    l := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    if index > 26 {
        letterA, _ := indexToColumn(int(math.Floor(float64(index-1)/26)))
        letterB, _ := indexToColumn(index%26)
        return letterA + letterB, nil
    } else {
        if index == 0 {
            index = 26
        }
        return string(l[index-1]), nil
    }

}

// columnToIndex takes in A1 Notation & converts it to an index value
// Column A is index 1
// E.g. C == 3, AC == 29, ABC == 731
func columnToIndex(column string) (int, error) {

    // Calculate index from column string
    var index int
    var a uint8 = "A"[0]
    var z uint8 = "Z"[0]
    var alphabet = z - a + 1
    i := 1
    for n := len(column) - 1; n >= 0; n-- {
        r := column[n]
        if r < a || r > z {
            return 0, web.Errorf("invalid character in column, expected A-Z but got [%c]", r)
        }
        runePos := int(r-a) + 1
        index += runePos * int(math.Pow(float64(alphabet), float64(i-1)))
        i++
    }

    // Return column index & success
    return index, nil

}

到这里,我们也就讲完了《将列表示法和索引互相转换》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>