栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

纯C实现的高效好用的Split

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

纯C实现的高效好用的Split

先上效果图,代码在最后

 


int StrUtil::Split(const char* str, const char* div, char* pStrs[])
{
	if (!div || !div[0]) { return -1; }

	// 计算所需最小内存
	auto getBytes = [&](int* pnStrs)->int {
		*pnStrs = 0;
		int nBytes = 0;
		char* p0 = (char*)str;
		for (char* p1 = strstr(p0, div); p1; p1 = strstr(p1 + 1, div))
		{
			++(*pnStrs);
			nBytes += (p1 - p0);
			nBytes += sizeof(char*);
			p0 = p1;
		}
		nBytes += strlen(p0) + 1 + sizeof(char*);
		++(*pnStrs);
		return nBytes;
	};

	int nStrs = 0;
	int nBytes = getBytes(&nStrs);

	if (!pStrs) { return nBytes; }

	// 函数要求pStrs必须满足大于等于nBytes,否则以下逻辑将导致内存溢出
	char* pBytes = (char*)pStrs;
	memset(pBytes, 0, nBytes);

	pStrs[0] = pBytes + nStrs * sizeof(char*);
	strcpy(pStrs[0], str);

	int len = strlen(str);
	int divlen = strlen(div);
	for (int i = nBytes, j = nBytes + 1, k = nStrs; i >= 0;--i)
	{ // i记录当前位置,j记录上个子串起始位置,l记录当前子串长度,k记录当前子串索引
		if (memcmp(&pBytes[i], div, divlen) == 0)
		{
			int l = j - i - divlen - 1;
			j = j - (l + 1); // 重计算为当前子串即将存储的位置
			pStrs[--k] = (char*)memmove(&pBytes[j], &pBytes[i + divlen], l);
			memset(&pBytes[i], 0, j - i);
		}
	}

	return nStrs;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/675658.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号