如何从字符串中获取最后一个字符



我想在列表字符串中获得重量和对象(在本例中,我想获得整数501和字符串"kg bag of sugar")。但我不知道may在整数后面串。但我确实知道整数之前和之后有多少个空格(这就是为什么我做+3,因为整数之前有2个空格,最后有1个空格)。我得到了一个分割错误在我的代码。

这是我正在尝试做的一个例子。

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
/* get the weight and the object */
int main(void) {   
char line[50] = "  501 kg bag of sugar"; //we don't know how many char after integer 
char afterint[50];
long int weight, weight2;
int lenofint;
sscanf(line, "%ld", &weight);
weight2 = weight;
while (weight2 != 0) {
weight2 = weight2 / 10;
lenofint++;
}

afterint[0] = line[lenofint + 3]; // +3 since there are 2 spaces before integer and 1 space at the end
//printf("%c", afterint);
for (int j = 1; j < (strlen(line) - lenofint - 3); j++) {
afterint[j] = afterint[j] + line[j + lenofint + 3];
}
printf("%s", afterint);
}

不要再硬编码偏移量了,这对你来说太难了。scanf系列函数包括一个选项%n,它将告诉您在此之前扫描中已处理了多少字符。从这里你可以跳过空白,继续标签的其余部分。

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char line[50] = "  501 kg bag of sugger";
long int weight;
int count;
if (sscanf(line, "%ld%n", &weight, &count) == 1)
{
char *suffix = line+count;
while (*suffix && isspace((unsigned char)*suffix))
++suffix;
puts(suffix);
}
}

kg bag of sugger

作为奖励,通过使用此方法,您还可以进行错误检查。注意检查sscanf的返回结果,它表示成功解析参数的次数。如果这不是1,则意味着缓冲区前导位置中的任何内容都不能成功解析为%ld(long int),因此其余部分毫无意义。

您可以使用strtol()读取数字并获得指向数字后面的字符串中的点的指针。然后它将指向kg bag of sugar。这样就不需要对数字进行反向计算了。在任何情况下,数字都可能有前导零之类的,所以无论如何都无法从数值中知道字符长度。

然后跳过从strtol得到的指针中的空白。

#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char *foo = "  501 kg bag of sugar";
char *thing = NULL;
int weight = 0;
weight = strtol(foo, &thing, 10);
while (isspace(*thing)) {
item++;
}
printf("weight: %d thing: %sn", weight, thing);
}

或者,我认为您可以执行类似sscanf(foo, "%d %100c", &weight, buffer);的操作来获取数字和下面的字符串。(我将把它留给你选择一个比%100c更健康的转换。)

最新更新