文字列をカンマで分割し、二次元配列を形成し、結果をC/C++に伝える

3073 ワード

次の特徴("abcdef,acccd,eeee,aaa,e 3 eeeee,sssss,")に合致する文字列があり、関数(インタフェース)を書き、次の結果を出力する必要があります.
1)文字列をカンマで分割し,2次元配列を形成し,結果を伝達する.
2)2次元配列行数演算結果も出力する.
int getStrArray(const char *src, char dst[100][100])      
{      
    int i = 0,j = 0, nLength  = 0;      
    char *curStart = src; 
    char *lastStart = src;

    do 
    {
        curStart = strstr(curStart, ",");
        nLength = curStart - lastStart;  
        memcpy(dst[i++], lastStart, nLength);      
        lastStart = ++curStart;      
    } while (*curStart != '\0');   
    return 0;      
}      
int main()      
{      
    char *src = "abcdef,acccd,eeee,aaaa,e3eeeee,sssss,";      
    char dst[100][100] = {0};      
    getStrArray(src, dst);      
    return 0;      
}  

また、2 Dポインタモデルを別の2 Dポインタモデルで実現することもできます.
void printfArr(char **arrayPtr, int nLength)  
{  
    int i = 0;  
    for (; i < nLength; i++)  
    {  
        printf("%s
", arrayPtr[i]); } } int getStrArray(const char *src, char **dst) { int i = 0,j = 0, nLength = 0; char *curStart = src; char *lastStart = src;
do 
{
    curStart = strstr(curStart, ",");
    nLength = curStart - lastStart;  
    memcpy(dst[i++], lastStart, nLength);      
    lastStart = ++curStart;      
} while (*curStart != '\0');   
return 0;      
}
int main()
{
int j = 0;
int i =0;
char *src = “abcdef,acccd,eeee,aaaa,e3eeeee,sssss,”;
char dst = (char )malloc(10 * sizeof(char *));
if (!dst)
{
    return -1;
}
for (; i < 10; i++)
{
    dst[i] = (char *)malloc(100);
    memset(dst[i],'\0',100);
}

getStrArray(src, dst); 

printfArr(dst, 10);

for (i = 0; i < 10; i++)
{
    free(dst[i]);
}
free(dst);
return 0;      
}
//全部で何行に分けますか
void getLine(char *str, char c, int *line){
char *p = str;
char *q = str;
int num = 0;
while (*p != ‘\0’){
if (*p == c){
num++;
}
p++;
}
num = num + 1;
*line = num;
}
char ** getData(char *str, char c, int line){
char *p = str;
char *q = str;
char **result = (char **)malloc(line*sizeof(char*));
for (int i = 0; i < line; i++){
    while (*q != '\0' && *q != c){//                c
        q++;
    }
    char *part = (char *)malloc(100 * sizeof(char));
    int length = q - p;
    memcpy(part, p, length);//    
    part[length] = '\0';

    p = q + 1 ;
    q = q + 1;
    result[i] = part;       
}
return result;
};
void main(){
char *str =”abcdef,acccd,eeee,aaaa,e3eeeee,sssss”;
int line = (int )malloc(1*sizeof(int));
char c = ‘,’;
getLine(str, c, line);
printf(“%s文字列は%d行に分けることができます”,str,*line);
char ** result = getData(str, c, *line);
printf(「分割された文字列配列データ:」);
for (int i = 0; i < *line; i++){
printf(“%s”,result[i]);
}
system(“pause”);
}