我有一串这样的数字:160 01 11 12 33 44 44 ...我想从头开始分割,直到第一个空格这样:160 | 01 11 12 33 44 44.... 例如,我可以将字符串放在数组中的第一个空格之前,并将字符串放在其他数组中。
arr1 [] = '160'
arr2[]='01 11 12 33 44 44...'
我从文件中提取这种类型的字符串,所以我的代码是这样的:
int le_ficheiro(char* filename) {
FILE *ficheiro=fopen(filename,"r");
size_t len=0;
char *line=NULL;
ssize_t read;
if(ficheiro==NULL) {
exit(EXIT_FAILURE);
}
while((read = getline (&line, &len,ficheiro))!=-1) //read line by line
{
printf("Retrieved line of length %zu:\n",read);
printf("%s\n",line);
printf("Aqui : %c\n",line[0]);
}
fclose(ficheiro);
if(line)
free(line);
exit(EXIT_SUCCESS);
我需要一些帮助来了解如何做到这一点。
您可以使用strtok
拆分字符串。这是手册页。
在这种特定情况下,找到第一个空格并拆分就足够了。
char *s1;
char *s2;
char *sp;
sp = strchr(line, ' ');
if (!sp) { exit(EXIT_FAILURE); }
s1 = strndup(line, sp-line); /* Copy chars until space */
s2 = sp+1; /* Skip the space */
...
free(s1);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句