我从C socket recv函数中获取了这样的字符串,并想知道如何处理它并获取字符串上字母(S,L,E ...)旁边的数值

S@AB@L1550 @W
>E0578A9069C0000
>S0223W0418
>R2219H1429S0000
>G0156V0116T1800
>m0138
>m0087


例如字母,需要将数字223和其他数字相同;

正在考虑做一个循环并读取所有向量并检查关键字。
但不确定是否有更简单或更快速的方法

最佳答案

这段代码演示了完成这项工作的一种方法。

/* SO 4635-2633 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    char data[] =
        "S@AB@L1550 @W\n"
        ">E0578A9069C0000\n"
        ">S0223W0418\n"
        ">R2219H1429S0000\n"
        ">G0156V0116T1800\n"
        ">m0138\n"
        ">m0087";
    const char digits[] = "0123456789";

    printf("Raw data:\n[%s]\n", data);

    size_t offset = 0;
    size_t skip;
    //for (skip = strcspn(data + offset, digits);
    //     data[skip] != '\0';
    //     skip = strcspn(data + offset, digits))
    while (data[(skip = strcspn(data + offset, digits))] != '\0')
    {
        size_t len = strspn(data + offset + skip, digits);
        if (len == 0)
            break;
        char numstr[32];
        memmove(numstr, data + offset + skip, len);
        numstr[len] = '\0';
        int number = atoi(numstr);
        printf("Number %4d (position %2zu..%-2zu - [%.*s])\n",
               number, offset + skip, offset + skip + len - 1,
               (int)len, data + offset + skip);
        offset += skip + len;
    }

    return 0;
}


运行时,输出为:

Raw data:
[S@AB@L1550 @W
>E0578A9069C0000
>S0223W0418
>R2219H1429S0000
>G0156V0116T1800
>m0138
>m0087]
Number 1550 (position  6..9  - [1550])
Number  578 (position 16..19 - [0578])
Number 9069 (position 21..24 - [9069])
Number    0 (position 26..29 - [0000])
Number  223 (position 33..36 - [0223])
Number  418 (position 38..41 - [0418])
Number 2219 (position 45..48 - [2219])
Number 1429 (position 50..53 - [1429])
Number    0 (position 55..58 - [0000])
Number  156 (position 62..65 - [0156])
Number  116 (position 67..70 - [0116])
Number 1800 (position 72..75 - [1800])
Number  138 (position 79..82 - [0138])
Number   87 (position 86..89 - [0087])


您可以使用for循环代替while循环,但要以重复调用strcspn()为代价。我宁愿不重复自己。

10-04 13:33