C语言实现字符串split

面向对象的语言对于字符串的处理都有split操作,可以方便的将字符串分割。今天我自己用C语言实现了字符串分割将分割结果保存在字符串指针数组中。

#include "string.h"
#include <stdio.h>
#include <stdlib.h>

char** strsplit(char *str, char stok)
{
	char *p = str, *h = str, *item = NULL;
	char **ret = NULL, **index;
	int size = 0;
	while(*p)
	{
		if(*p == stok)
			size++;
		p++;
	}
	ret = (char **)malloc((size+2) * sizeof(char *));
	if(ret == NULL)
		return NULL;
	p = str;
	index = ret;
	while(*p)
	{
		if(*p == stok)
		{
			size = p - h-1;
			item = (char *)malloc((size+1)*sizeof(char));
			if(h == str)
				memcpy(item, h,size+1);
			else
				memcpy(item, h+1,size);
			h = p;
			*index = item;
			index++;
		}
		p++;
	}
	size = p - h-1;
	item = (char *)malloc(size*sizeof(char));
	memcpy(item, h+1,size);
	*index = item;
	*(index + 1) = NULL;
	return ret;
}

上面的函数用malloc函数动态的分配了内存空间,使用完成后需要利用free函数将分配的内存空间释放。所以,在使用上面函数处理字符串后需要将内存空间释放掉。因此,我实现了下面的内存空间释放函数。

void strfreesplitp(char **spl)
{
	char **sp = spl;
	while(*sp)
	{
		sp++;
		free(*(sp-1));
	}
	free(spl);
}

当然,如果给出使用的例子会更加的有利于其他人的参考。接下来就给出一个简单的例子。

int main(int argc, char** argv)
{
	char *str = "aa,bb,cc,dd,ee";
	char **sp = strsplit(str, ',');
	char **index = sp;
	while(*index)
	{
		printf("%s ", *index);
		index++;
	}
	strfreesplitp(sp);
}

无论是函数还是函数使用的例子都用到了许多的指针,对应一些对指针使用不是很熟练的同学可能看的一头雾水。后续我如果有时间会对程序中的指针做出解释。

发布了23 篇原创文章 · 获赞 27 · 访问量 1166

猜你喜欢

转载自blog.csdn.net/BLUCEJIE/article/details/103455515