如何在点上拆分字符串并有效地提取所有字段

How to split the string on a dot and extract all the fields efficiently?

本文关键字:有效地 串并 提取 字段 字符串 字符 拆分      更新时间:2023-10-16

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

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

t26.example.1136580077.colox

目前,我只能提取在第一个点上拆分后t26的第一个字段。现在我不确定如何使用下面的代码提取所有其他字段,它更像 C。

下面是我目前用来从中提取第一个字段的代码。

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

在点上分裂后。我的第一个字段将是string,在本例中为 t26,第二个字段也将string在本例中为 example,第三个字段将uint64_t在本例中为 1136580077,第四个字段也将是字符串,在本例中为 colox

任何想法如何有效地完成这项工作?与istringstream相比,使用strtok更有效

#include <stdint.h>
#include <vector>
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
vector<string> spilt(char str[])
{
    vector<string> res;
    char* p;
    char* totken = strtok_s(str, ".", &p);
    while(totken != NULL)
    {
         res.push_back(totken);
         totken = strtok_s(NULL, ".", &p);
    }
    return res;
}
int main()
{
    char str[] = "t26.example.1136580077.colox";
    vector<string> res = spilt(str);
    string field1 = res[0];
    string field2 = res[1];
    uint64_t field3 = atoi(res[2].c_str());
    string field4 = res[3];
    cout<<field1<<" "<<field2<<" "<<field3<<" "<<field4<<endl;
}

编写一个拆分字符串并限定键组件的函数。鉴于您对效率的关注,请使用 strchr 定位点,并使用 strncpy 提取组件值,其中 strncpy 的长度由指针增量确定。

下面是一些未经测试的伪代码:

const int MAX_COMP_SIZE = 256;
int count = 0;
const char *p = key;
if (p != NULL) 
{
    char comp[MAX_COMP_SIZE];
    const int CompSize = sizeof(comp)/sizeof(comp[0]);
    while (*p != '')
    {
        const char *q = strchr(p, '.');
        if (q != NULL)
        {
            int len = q - p;
            if (len >= CompSize)
                return -1;
            strncpy(comp, p, q-p)[len] = '';
        }
        else
        {
            if (strlen(p) >= CompSize)
                return -1;
            strcpy(comp, p);
        }
        // store/verify key components based on index, count
        // implement in separate function
        switch(count)
        {
            case 0: ...
            case 1: ...
            default: return -1;
        }
        count++
        if (q == NULL)
            break;
        q++; // skip dot
        p = q; // setup next
    }
}   
if (count < REQUIRED_KEY_COMPONENTS)
    return -1;