将字符串拆分为点,并在C++中提取所有字段

Split the string on dot and extract all the fields from it in C++?

本文关键字:提取 字段 C++ 并在 拆分 字符串      更新时间:2023-10-16

我正在尝试在点上拆分我的实际键,然后在将其拆分为点后从中提取所有字段。

我的钥匙看起来像这样——

@event.1384393612958.1136580077.TESTING

目前,我只能提取在点上拆分后@event的第一个字段。现在如何提取所有其他字段。下面是我的代码,我目前正在使用从中提取第一个字段。

if (key)
{
    char* first_dot = strchr(key, '.');
    if (first_dot)
    {
        // cut at the first '.' character
        first_dot[0] = 0;
    }
}
cout << "Fist Key: " << key << endl;

然后在提取单个字段后,将第二个字段存储为 uint64_t,第三个字段存储为 uint32_t,最后一个字段存储为 string

更新:-

这就是我现在得到的——

if (key)
{
char *first_dot = strtok(key, ".");
char *next_dot = strtok(NULL, ".");
uint64_t secondField = strtoul(next_dot, 0, 10);
cout << first_dot << endl;
cout << secondField << endl;
}

我能够从中提取第一个和第二个字段。第三和第四领域呢?

你可以

改用strtokstrtok确实如此,你现在正在做的事情。当遇到分隔字符时,它会拆分字符串

if (key) {
    char *first_dot = strtok(key, ".");
    ...
    char *next_dot = strtok(NULL, ".");
}

转换为某些int类型可以使用strtoul/strtoull

uint64_t i = strtoul(next_dot, 0, 10);