C中的指针和字符串解析
我想知道是否有人可以向我解释指针和字符串解析的工作原理。我知道我可以在循环中执行类似以下操作,但我仍然不太了解它是如何工作的。
for (a = str; * a; a++) ...
例如,我试图从字符串中获取最后一个整数。如果我有一个字符串 const char *str = "some string here 100 2000";
使用上面的方法,我如何解析它并获取字符串的最后一个整数 (2000),知道最后一个整数 (2000) 可能会有所不同。
谢谢
I was wondering if somebody could explain me how pointers and string parsing works. I know that I can do something like the following in a loop but I still don't follow very well how it works.
for (a = str; * a; a++) ...
For instance, I'm trying to get the last integer from the string. if I have a string as const char *str = "some string here 100 2000";
Using the method above, how could I parse it and get the last integer of the string (2000), knowing that the last integer (2000) may vary.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是通过在字符串开头启动一个指针
a
来实现的,直到取消引用a
code> 隐式转换为 false,在每一步递增a
。基本上,您将遍历数组,直到到达字符串末尾的 NUL 终止符 (
\0
),因为 NUL 终止符会隐式转换为 false - 其他字符不会。您需要查找
\0
之前的最后一个空格,然后您需要调用一个函数将剩余字符转换为整数。请参阅strtol
。考虑这种方法:
strtol
。-
或者,只需跟踪最后一个标记的开头:
此版本的优点是不需要字符串中的空格。
This works by starting a pointer
a
at the beginning of the string, until dereferencinga
is implicitly converted to false, incrementinga
at each step.Basically, you'll walk the array until you get to the NUL terminator that's at the end of your string (
\0
) because the NUL terminator implicitly converts to false - other characters do not.You're going to want to look for the last space before the
\0
, then you're going to want to call a function to convert the remaining characters to an integer. Seestrtol
.Consider this approach:
strtol
.-
Or alternatively, just keep track of the start of the last token:
This version has the benefit of not requiring a space in the string.
您只需要实现一个具有两种状态的简单状态机,例如
You just need to implement a simple state machine with two states, e.g
我知道这个问题已经得到解答,但迄今为止的所有答案都是重新创建标准 C 库中可用的代码。这是我将通过利用
strrchr()
输出来使用的内容
I know this has been answered already but all the answers thus far are recreating code that is available in the Standard C Library. Here is what I would use by taking advantage of
strrchr()
Output
相当于
is equivalent to
您提供的循环仅遍历所有字符(字符串是指向以 0 结尾的 1 字节字符数组的指针)。为了进行解析,您应该使用
sscanf
或更好的C++
的字符串和字符串流。The loop you've presented just goes through all characters (string is a pointer to the array of 1-byte chars that ends with 0). For parsing you should use
sscanf
or betterC++
's string and string stream.