如何在点上拆分字符串并有效地提取所有字段
How to split the string on a dot and extract all the fields efficiently?
>我正在尝试将我的实际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;
相关文章:
- 有效地使用std::unordered_map来插入或增加键的值
- 如何有效地在 std::vector 中插入一对?
- 有效地计算多维数组的累积和?
- 如何有效地计算将单位立方体映射到自身的反射和旋转?
- 有效地将大数存储为 2 的幂用于路径问题
- 如何在C++中写入 1000 个文件时有效地缓冲
- 如何有效地找到数组中三元组和的最小差异?
- 如何在C++中有效地将数字值重新分配给字符数组
- 我们怎样才能有效地压缩DNA串
- 如何避免使用 goto 并有效地中断嵌套循环
- 如何在函数中初始化矩阵并在C++中有效地返回它
- 有效地在小环上使用OpenMP,并具有非常大的嵌套回路
- 如何在 C++11 中的类这样的位集中有效地支持"子位串"?
- 我如何有效地清理此程序并仍然检测文件输入何时不是字母
- 如何在点上拆分字符串并有效地提取所有字段
- 在 c++ 中存储对象的最佳策略是什么,确保名称唯一并能够在以后有效地检索它们
- Linux,介绍如何运行子二进制文件并有效地传递有效负载
- opencv Qt如何有效地创建彩色图像并将其传递给QImage
- 有效地解释串行数据
- 从文件中读取并有效地向树中添加单词