Rob*_*t74 5 c pointers string-parsing
我想知道是否有人可以解释指针和字符串解析是如何工作的.我知道我可以在循环中执行类似下面的操作,但我仍然不能很好地遵循它的工作原理.
for (a = str; * a; a++) ...
Run Code Online (Sandbox Code Playgroud)
例如,我正在尝试从字符串中获取最后一个整数.如果我有一个字符串const char *str = "some string here 100 2000";
使用上面的方法,我怎么能解析它并获得字符串的最后一个整数(2000),知道最后一个整数(2000)可能会有所不同.
谢谢
for (a = str; * a; a++) ...
这通过a在字符串的开头启动指针来工作,直到解除引用a被隐式转换为false,a在每一步递增.
基本上,你将遍历数组,直到你到达字符串末尾\0的NUL终结符(),因为NUL终结符隐式转换为false - 其他字符不会.
使用上面的方法,我怎么能解析它并获得字符串的最后一个整数(2000),知道最后一个整数(2000)可能会有所不同.
你会想要去寻找最后一个空格前的\0,那么你将要调用一个函数所剩的字符转换为整数.见strtol.
考虑这种方法:
strtol.-
for (a = str; *a; a++); // Find the end.
while (*a != ' ') a--; // Move back to the space.
a++; // Move one past the space.
int result = strtol(a, NULL, 10);
Run Code Online (Sandbox Code Playgroud)
或者,只需跟踪最后一个令牌的开头:
const char* start = str;
for (a = str; *a; a++) { // Until you hit the end of the string.
if (*a == ' ') start = a; // New token, reassign start.
}
int result = strtol(start, NULL, 10);
Run Code Online (Sandbox Code Playgroud)
此版本的好处是不需要字符串中的空格.