使用C语言实现字符串分割

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/r5014/article/details/83143667

之前分享了一篇使用C++(std::string 作为容器)进行字符串分割的博文:

https://blog.csdn.net/r5014/article/details/82802664

现在又想用C语言做一个字符串分割的函数,大概功能是这样:

需要分割的字符串“    this is a charactor  raw.    ” 使用 ' '分割

分割之后会返回一个char** strv 表示分割出子串str的vector,返回一个int strc表示分割出子串的数量,在使用完毕之后自行释放strv

strv可能是NULL 比如"      "使用‘ ’分割之后就是NULL。

以下介绍分割函数splitstr_c()

//* 切割字符串,strv返回字符串数组,strc返回分割之后的字符串数量
void splitstr_c(char* str, char c, char*** strv, int* strc)
{
    int    i = 0;
    int    j = 0;
    int    n = 0;
    int    offset_strv = 0;
    int    offset_font = 0;
    int    offset_back = 0;
    int    str_size = strlen(str);
    char** tstrv = NULL;


    for(i = 0; i < str_size; i++)
    {
		if(i > 0)
		{
			if((str[i] != c) && (str[i - 1] == c))
			{
				n++;
			}
		}
		else
		{
			if(str[0] != c)
			{
				n++;
			}
		}
    }
	if(n == 0)
	{
		 for(i = 0; i < str_size; i++)
		 {
			if(str[i] != c)
			{
				n++;
				break;
			}
		 }
	}
		


    * strc = n;
    tstrv = (char**)malloc(sizeof(char*) * n);
    memset(tstrv, 0, sizeof(char*)*n);

    for(i = 0; i < str_size; i++)
    {
        if(str[i] == c)
        {
            offset_back = i;
            if(offset_back != offset_font)
            {
                n = offset_back - offset_font;
                char* sub_str = (char*)malloc(sizeof(char) * (n + 1)); //* n + 1是为了容纳'\0'
                memset(sub_str, 0, sizeof(char) * (n + 1));
                memcpy(sub_str, str + offset_font, n);
                tstrv[offset_strv] = sub_str;
                offset_strv++;
            }

            offset_font = offset_back + 1;
        }
    }

    if(offset_back < str_size)
    {
        offset_back = str_size;

        if(offset_back != offset_font)
        {
            n = offset_back - offset_font;
            char* sub_str = (char*)malloc(sizeof(char) * (n + 1));
            memset(sub_str, 0, sizeof(char) * (n + 1));
            memcpy(sub_str, str + offset_font, n);
            tstrv[offset_strv] = sub_str;
            offset_strv++;
        }

        offset_font = offset_back + 1;
    }

    * strv = tstrv;
}

顺带给出两个小工具函数:

//* print strv
void print_strv(char** strv, int strc)
{
	if(strc > 0)
	{
		for(int i = 0; i < strc; i++)
		{
			printf("%s\n",strv[i]);
		}
	}
}

//* strv使用完之后根据strc来进行释放。
void free_strv(char** strv, int strc)
{
	if(strc > 0)
	{

		for(int i = 0; i < strc; i++)
		{

			//printf("%s\n",strv[i]);
			free(strv[i]);
		}

		free(strv);
	}
}

让我们来试一下:

char  *text = "   this  is a charactor text.    ";
//char  *text = "000this00is0a0charactor0text.00";
//char  *text = "this is a charactor text.";
//char *text = "a  a a    a     s  ";

char** strv = NULL;
int    strc = 0;

splitstr_c(text, ' ', &strv, &strc);

printf("splitstr_c: %d\n", strc);
print_strv(strv, strc);
free_strv(strv, strc);

结果:

自此这个功能就实现了

猜你喜欢

转载自blog.csdn.net/r5014/article/details/83143667