我想知道指针和字符串解析是如何工作的,请帮忙解释一下。我知道我可以在循环中执行以下操作,但我仍然不太明白它的工作原理。
for (a = str; * a; a++) ...
例如,我正在尝试从字符串中获取最后一个整数。如果我有一个字符串
const char *str = "some string here 100 2000";
,那么如何解析它并获取字符串的最后一个整数(2000),知道最后一个���数(2000)可能会变化。谢谢。
我想知道指针和字符串解析是如何工作的,请帮忙解释一下。我知道我可以在循环中执行以下操作,但我仍然不太明白它的工作原理。
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,而其他字符则不会。
通过以上的方法,我怎么能解析它并获取字符串中的最后一个整数(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);
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);
这个版本的好处是不需要在字符串中加空格。
a = str + strlen(str)
指向字符串的最后一个字节(null 字节)之后的字节;这与 for
循环几乎相同,但更易读,我认为;此外,您可以使用 isspace 而不是 *a != ' '
。 - ShinTakezoustrlen
,但是OP说“使用上述方法”,所以我就这样做了... 另一方面,isspace
可能更清晰。 - Stephen您只需要实现一个简单的状态机,它有两个状态,例如
#include <ctype.h>
int num = 0; // the final int value will be contained here
int state = 0; // state == 0 == not parsing int, state == 1 == parsing int
for (i = 0; i < strlen(s); ++i)
{
if (state == 0) // if currently in state 0, i.e. not parsing int
{
if (isdigit(s[i])) // if we just found the first digit character of an int
{
num = s[i] - '0'; // discard any old int value and start accumulating new value
state = 1; // we are now in state 1
}
// otherwise do nothing and remain in state 0
}
else // currently in state 1, i.e. parsing int
{
if (isdigit(s[i])) // if this is another digit character
{
num = num * 10 + s[i] - '0'; // continue accumulating int
// remain in state 1...
}
else // no longer parsing int
{
state = 0; // return to state 0
}
}
}
const char *
,编译器可能会为你优化)。 - Tim Schaeffer我知道这个问题已经有答案了,但到目前为止所有的答案都在重新创建标准C库中可用的代码。这是我会使用的方法,利用strrchr()
#include <string.h>
#include <stdio.h>
int main(void)
{
const char* input = "some string here 100 2000";
char* p;
long l = 0;
if(p = strrchr(input, ' '))
l = strtol(p+1, NULL, 10);
printf("%ld\n", l);
return 0;
}
2000
for (a = str; * a; a++)...
等同于
a=str;
while(*a!='\0') //'\0' is NUL, don't confuse it with NULL which is a macro
{
....
a++;
}
sscanf
或更好的C++
的字符串和字符串流。