int split(char dst[][80], char* str, const char* spl)
创新互联公司主营宜都网站建设的网络公司,主营网站建设方案,重庆APP软件开发,宜都h5微信小程序开发搭建,宜都网站营销推广欢迎宜都等地区企业咨询
{
int n = 0;
char *result = NULL;
result = strtok(str, spl);
while( result != NULL )
{
strcpy(dst[n++], result);
result = strtok(NULL, spl);
}
return n;
}
int _tmain(int argc, _TCHAR* argv[])
{
char str[] = "123,456\n789,321";
char dst[10][80];
int cnt = split(dst, str, "\n");
for (int i = 0; i cnt; i++)
puts(dst[i]);
return 0;
}
主要是字符串分割函数strtok的使用
#include stdio.h
#include string.h
// 将str字符以spl分割,存于dst中,并返回子字符串数量
int split(char dst[][80], char* str, const char* spl)
{
int n = 0;
char *result = NULL;
result = strtok(str, spl);
while( result != NULL )
{
strcpy(dst[n++], result);
result = strtok(NULL, spl);
}
return n;
}
int main()
{
char str[] = "what is you name?";
char dst[10][80];
int cnt = split(dst, str, " ");
for (int i = 0; i cnt; i++)
puts(dst[i]);
return 0;
}
C标准库中提供了一个字符串分割函数strtok();
实现代码如下:
#include stdio.h
#include string.h
#define MAXSIZE 1024
int main(int argc, char * argv[])
{
char dates[MAXSIZE] = "$GPGGA,045950.00,A,3958.46258,N,11620.55662,E,0.115,,070511,,,A*76 ";
char *delim = ",";
char *p;
printf("%s ",strtok(dates,delim));
while(p = strtok(NULL,delim))
{
printf("%s ",p);
}
printf("\n");
return 0;
}
运行结果截图如下:
可以写一个分割函数,用于分割指令,比如cat a.c最后会被分割成cat和a.c两个字符串、mv a.c b.c最后会被分割成mv和a.c和b.c三个字符串。
参考代码如下:
#include stdio.h
#includestring.h
#define MAX_LEN 128
void main()
{
int i,length,ct=0,start = -1;
char inputBuffer[MAX_LEN],*args[MAX_LEN];
strcpy(inputBuffer,"mv a.c b.c");
length=strlen(inputBuffer);
for (i = 0; i = length; i++) {
switch (inputBuffer[i]){
case ' ':
case '\t' : /* argument separators */
if(start != -1){
args[ct] = inputBuffer; /* set up pointer */
ct++;
}
inputBuffer[i] = '\0'; /* add a null char; make a C string */
start = -1;
break;
case '\0': /* should be the final char examined */
if (start != -1){
args[ct] = inputBuffer;
ct++;
}
inputBuffer[i] = '\0';
args[ct] = NULL; /* no more arguments to this command */
break;
default : /* some other character */
if (start == -1)
start = i;
}
}
printf("分解之后的字符串为:\n");
for(i=0;ict;i++)
printf("%s \n",args[i]);
}
用strtok函数实现吧。
void split( char **arr, char *str, const char *del)//字符分割函数的简单定义和实现
{
char *s =NULL;
s=strtok(str,del);
while(s != NULL)
{
*arr++ = s;
s = strtok(NULL,del);
}
}
int main()
{
int i;
char *myArray[4];
char s[] = "张三$|男$|济南$|大专学历$|";
memset(myArray, 0x0, sizeof(myArray));
split(myArray, s, "$|");
for (i=0; i4; i++)
{
printf("%s\n", myArray[i]);
}
return 0;
}