获取子串的索引
我有 char * source,我想从中提取内容,我知道它是从符号“abc”开始,并在源结束处结束。使用 strstr 我可以得到指针,但不能得到位置,并且没有位置我不知道子字符串的长度。纯C语言中如何获取子字符串的索引?
I have char * source, and I want extract from it subsrting, that I know is beginning from symbols "abc", and ends where source ends. With strstr I can get the poiner, but not the position, and without position I don't know the length of the substring. How can I get the index of the substring in pure C?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用指针减法。
Use pointer subtraction.
newptr - source
将为您提供偏移量。newptr - source
will give you the offset.这是带有偏移功能的 strpos 函数的 C 版本...
Here is a C version of the strpos function with an offset feature...
如果您有指向子字符串第一个字符的指针,并且子字符串在源字符串的末尾结束,则:
substring - source
将为您提供起始索引。If you have the pointer to the first char of the substring, and the substring ends at the end of the source string, then:
strlen(substring)
will give you its length.substring - source
will give you the start index.形式上,其他人是正确的 -
substring - source
确实是起始索引。但您不需要它:您可以将其用作source
的索引。因此,编译器将source + (substring - source)
计算为新地址 - 但只需substring
就足以满足几乎所有用例。只是优化和简化的提示。
Formally the others are right -
substring - source
is indeed the start index. But you won't need it: you would use it as index intosource
. So the compiler calculatessource + (substring - source)
as the new address - but justsubstring
would be enough for nearly all use cases.Just a hint for optimization and simplification.
通过起始词和结束词从字符串中剪切单词的函数
A function to cut a word out out of a string by a start and end word