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);
}

無論是函數還是函數使用的例子都用到了許多的指針,對應一些對指針使用不是很熟練的同學可能看的一頭霧水。後續我如果有時間會對程序中的指針做出解釋。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章