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

时间:2021-03-01 23:24:57

标签: c

我想在列表字符串中获取重量和对象(在本例中,我想获取整数 501 和字符串“kg bag of sugar”。但我不知道如何在整数之后字符串. 但我确实知道整数前后有多少个空格(这就是我做 +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);
}

2 个答案:

答案 0 :(得分:2)

停止硬编码偏移并让这对你自己很难。 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),因此其余部分毫无意义。

答案 1 :(得分:1)

您可以使用 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 更明智的转换。)