我想知道是否有人可以向我解释指针和字符串解析的工作原理。我知道我可以在循环中执行类似以下的操作,但我仍然不太了解它是如何工作的。
for (a = str; * a; a++) ...
例如,我试图从字符串中获取最后一个整数。如果我有一个字符串 const char *str = "some string here 100 2000";
使用上面的方法,我如何解析它并获取字符串的最后一个整数 (2000),知道最后一个整数 (2000) 可能会有所不同。
谢谢
最佳答案
for (a = str; * a; a++) ...
这通过在字符串的开头启动指针 a
来工作,直到取消引用 a
隐式转换为 false,递增 a
在每一步。
基本上,您将遍历数组,直到到达字符串末尾的 NUL 终止符 (\0
),因为 NUL 终止符隐式转换为 false - 其他字符不会。
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.
您将要查找 \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);
或者,只需跟踪最后一个标记的开始:
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);
此版本的优点是字符串中不需要空格。
关于c - c中的指针和字符串解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3127722/