[英]how to get a sub string from a string separated by commas in C
I want to get a sub array from a array in the programming language C 我想以编程语言C从数组中获取子数组
for instance if i have a char array: 例如,如果我有一个char数组:
c[]= "Peter,peter911@hotmail.com,213342,IGE
d[]= "JohnSilva,johnsilva@hotmail.com,213342,ETI
The thing is, i want a general code where when given an index, an array and a char that separates the index, it will put the following index, from a comma to another comma into a array.Index starts at 0 问题是,我想要一个通用代码,当给定一个索引,一个数组和一个用于分隔索引的字符时,它将把下面的索引(从逗号到另一个逗号)放入一个数组。索引从0开始
example : d[], index=1, separator: ',' 示例:d [],索引= 1,分隔符:“,”
the result= johnsilva@hotmail.com 结果= johnsilva@hotmail.com
main(){
char delimitador;
char linha[100];
int index;
printf("index\n");
scanf("%d",index);
printf("char delimitador\n");
scanf("%c",caractere);
printf("linha"\n");
scanf("%c",linha);
char vector[50];
int i=0;
int contador;
while(i!=index){
contador++;
if(c[contador]==delimitador){
strncpy(vector,linha,contador-1);
i++;
}
}
}
#include <stdio.h>
char *get_field(char *out_buff, const char *csv, int index, char separator){
int i;
char *p = out_buff;
for(i=0; i < index && *csv; ++csv){
if(*csv == separator)
++i;//count separator
}
if(i == index){
while( *csv && *csv != separator )
*p++ = *csv++;//cut out
}
*p = '\0';
return out_buff;
}
int main(void){
char d[]= "JohnSilva,johnsilva@hotmail.com,213342,ETI";
char vector[50];
get_field(vector, d, 1, ',');
puts(vector);
return 0;
}
Strtok function could be used . 可以使用Strtok函数。 But if you are not familiar with the function a simple char by char read of string could help .
但是,如果您不熟悉该功能,则简单的逐字符读取字符串的char可能会有所帮助。 Check this : http://wethecomputerguys.com/2014/12/10/break-string-using-index-and-separator/ .. Hope it helps you..
检查此: http : //wethecomputerguys.com/2014/12/10/break-string-using-index-and-separator/ ..希望它能对您有所帮助。
Read about string parsing, and then write a string parsing function that returns everything between the n-th comma and the next comma, then use an array of the form char *foo[]
. 阅读有关字符串解析的信息,然后编写一个字符串解析函数以返回第n个逗号和下一个逗号之间的所有内容,然后使用
char *foo[]
形式的数组。
String parsing: get number of commas, select desired one, get string between the two, make array. 字符串解析:获取逗号数量,选择所需的一个,在两者之间获取字符串,生成数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.