[英]How to get the last char from a string
我想在列表字符串中获取重量和 object(在此示例中,我想获取 integer 501 和字符串“kg bag of sugar”。但我不知道如何在 Z157DB7ZDF5300235672E851C 之后字符串。确实知道 integer 之前和之后有多少个空格(这就是为什么我做 +3 的原因,因为 integer 之前有 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
,它将告诉您在扫描中已经处理了多少个字符。 从那里您可以跳过空白并继续您的 label 的其余部分。
#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);
}
}
Output
kg bag of sugger
作为奖励,通过使用这种方法,您还可以获得错误检查。 请注意检查sscanf
的返回结果,它指示成功的参数解析次数。 如果不是1
,则意味着缓冲区中的任何内容 position 都无法成功解析为%ld
(long int),因此 rest 毫无意义。
您可以使用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: %s\n", weight, thing);
}
或者,我想你可以做类似sscanf(foo, "%d %100c", &weight, buffer);
获取数字和以下字符串。 (我会让你选择一个比%100c
更明智的转换。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.