如何在字节数组中找到字符串的行号?

huangapple go评论75阅读模式
英文:

How do you find the line number of a string in a byte array?

问题

我正在尝试找到的内容是:

  • 代码文件中的函数定义。

我已经拥有的信息是:

  • 代码文件。
  • 函数定义在代码文件中开始的字节索引和长度(以字节为单位)。

我应该如何找到该函数在文件中的行号?

我目前的想法是:

  • 将代码文件读取为字节数组。
  • 在字节数组中使用起始索引和长度找到函数。
  • 将该函数从二进制转换为文本。
  • 将整个代码文件从二进制转换为文本。
  • 对文本进行行编号。
  • 使用模式匹配找到函数在文本中的位置并返回行号。

我在后端使用的是 Golang,我相信它将执行这个功能。不过,我还有一个前端使用 JavaScript 的界面,如果需要的话,我可以利用它来帮助实现。

英文:

What I'm trying to find:

  • A function definition within a code file.

Information I have:

  • Code file.
  • The byte index of where the function definition starts in the code file and length in bytes.

How should I go about finding this function's line number in the file?

My current thoughts:

  • Read code file as byte array
  • Find function inside byte array by using start index and length for end.
  • Convert this function from binary to text.
  • Convert whole code file from binary to text.
  • Number the lines in the text.
  • Pattern match to find where the function is in the text and return line number.

I'm using Golang for the back-end service which I believe will execute this functionality. Though I also have a front-end in JavaScript which I can leverage to help if needed.

答案1

得分: 0

计算换行符的数量是否足够,或者你正在寻找更复杂的方法?

你可以从开始计算换行符\n,直到达到字节索引。
行号就是换行符的数量。

英文:

Would something like counting newline characters be good enough, or are you looking into something more tweaky?

You could just start counting newlines \n until you reach the byte index.
The line number is the number of newline characters.

答案2

得分: 0

假设你有一个类型为[]byte的文件内容变量p,以及一个表示函数的字节索引的整数变量i,那么bytes.Count(p[:i], []byte{'\n'}) + 1会返回该函数所在的行号。

英文:

Assuming that you have the contents of the file p as type []byte and the byte index of the function as int i, then bytes.Count(p[:i], []byte{'\n'}) + 1 returns the line number for the function.

huangapple
  • 本文由 发表于 2022年2月24日 01:06:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/71241228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定