C语言字符串切割
程序员文章站
2022-03-07 22:41:37
...
vim strsplit.c
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
static int strsplit(char *string, int stringlen,
char **tokens, int maxtokens, char delim)
{
int i, tok = 0;
int tokstart = 1; /* first token is right at start of string */
if (string == NULL || tokens == NULL)
goto einval_error;
for (i = 0; i < stringlen; i++)
{
if (string[i] == '\0' || tok >= maxtokens)
break;
if (tokstart)
{
tokstart = 0;
tokens[tok++] = &string[i];
}
if (string[i] == delim)
{
string[i] = '\0';
tokstart = 1;
}
}
return tok;
einval_error:
return -1;
}
int main(int argc ,char **argv)
{
char buf[150]="str1#str2#str3#str4";
int nb_token;
int i;
char *str_fld[5];
nb_token = strsplit(buf, sizeof(buf), str_fld, 4, '#');
for (i = 0; i < nb_token; i++)
{
if (i == 0)
{
printf("%d : %s\n",i,str_fld[i]);
}
else if (i == 1)
{
printf("%d : %s\n",i,str_fld[i]);
}
else if (i == 2)
printf("%d : %s\n",i,str_fld[i]);
}
}
编译
gcc strsplit.c -o strsplit
执行
./strsplit
结果
0 : str1
1 : str2
2 : str3
上一篇: gitignore 不起作用