C语言中 strchr() strncpy()的用法 以及根据某个字符切割字符串

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
//strchr() strncpy()的用法 以及根据某个字符切割字符串
int splitString(char* p1, char c, char buffer[10][30], int *count) {
	char* p = NULL, *pTmp = NULL;
	int tempCount = 0;
	p = p1;
	pTmp = p1;
	while (*p!='\0') {
		p = strchr(p, c);//检查符合条件的位置p 后移 
		if (p!=NULL)
		{
			if (p-pTmp>0)//算出符合条件具体的指针位置
			{
				strncpy(buffer[tempCount],pTmp,p-pTmp);
				buffer[tempCount][p - pTmp] = '\0';//变成C风格的字符串
				tempCount++;
				pTmp = p = p + 1;
			}
		}
		else {
			break;
		}

	}
	*count = tempCount;//具体有几个分割的字符串
	return 0;
}


void main() {
	int ret = 0, i = 0;
	char* p1 = "abcdef,acccd,bddddfdf,ffff,kjkjlkjkl";
	char splitC = ',';
	int nCout;
	char myArray[10][30];
	ret = splitString(p1, splitC, myArray, &nCout);
	for (i = 0; i < nCout; i++)
	{
		printf("%s\n",myArray[i]);
	}

	system("pause");
}

你可能感兴趣的:(C/C++)