英文:
How to compute the offset from column and line number ? - Go
问题
我需要使用列号和行号作为参考来计算源代码文件中的偏移量(例如source.go:23:42
)。如何计算偏移量?我正在使用一些Go工具(oracle、ast和token)来分析源代码。
英文:
I need to compute the offset in a source code file using a column and line number as reference (e.g. source.go:23:42
). How can I compute the offset ? I'm using it to analyse the source code with some go tools(oracle, ast and token).
答案1
得分: 2
由于行宽不固定,无法快速知道偏移量。您需要逐个字符遍历文件内容并计算偏移量。可以使用以下类似的代码:
func findOffset(fileText string, line, column int) int {
// 记录当前行和列的位置
currentCol := 1
currentLine := 1
for offset, ch := range fileText {
// 检查是否找到了目标位置
if currentLine == line && currentCol == column {
return offset
}
// 换行符 - 增加行计数器并重置列
if ch == '\n' {
currentLine++
currentCol = 1
} else {
currentCol++
}
}
return -1 // 未找到
}
// 这是我们的源代码示例
var sampleText = `package main
var foo = "hello"
var bar = "world"
`
func main() {
fmt.Println(findOffset(sampleText, 1, 1)) // 输出 0
fmt.Println(findOffset(sampleText, 3, 5)) // 输出 18
}
Playground链接:http://play.golang.org/p/fWb9N9r9pi
英文:
Since line width isn't fixed, there's no quick way of knowing that. you need to traverse the file's content character by character and count the offset. something like:
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
}
Playground link: http://play.golang.org/p/fWb9N9r9pi
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论