如何计算列和行号的偏移量? - 走

时间:2015-01-18 10:02:39

标签: go

我需要使用列和行号作为参考来计算源代码文件中的偏移量(例如source.go:23:42)。我该如何计算偏移量?我使用它来使用一些go工具(oracleasttoken)来分析源代码。

1 个答案:

答案 0 :(得分:1)

由于线宽不固定,因此无法快速了解。您需要逐个字符遍历文件的内容并计算偏移量。类似的东西:

func findOffset(fileText string, line, column int) int {
   // we count our current line and column position
   currentCol := 1
   currentLine := 1


   for offset,ch := range fileText {
      // see if we found where we wanted to go to
      if currentLine == line && currentCol == column {
         return offset
      }

      // line break - increment the line counter and reset the column
      if ch == '\n' {
         currentLine++
         currentCol = 1
      } else {
          currentCol++
      }

    } 
    return -1; //not found
} 

// this here is our source code for example
var sampleText = `package main

var foo = "hello"

var bar ="world"
`


func main() {

      fmt.Println(findOffset(sampleText, 1, 1)) //prints 0

      fmt.Println(findOffset(sampleText, 3, 5)) //prints 18

}

游乐场链接:http://play.golang.org/p/fWb9N9r9pi