答案 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
}