天天看點

C語言中 strchr() strncpy()的用法 以及根據某個字元切割字元串

#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
//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");
}
           

繼續閱讀