0

簡単な質問:

入力ファイルに次のような行がある場合:

Hello#Great#Day#Today

各単語を独自の配列として個別にスキャンするにはどうすればよいですか。つまり、C に # 文字に到達したらスキャンを停止し、ループの次の反復に進み、次の単語を別の配列としてスキャンするように指示しますか?

4

3 に答える 3

0

2段階で、次のようなものを使用しました:

#include <ansi_c.h>

//tokenizing a string
int GetCount(char *in, char *delim, int *m);
int GetStrings(char *in, char *delim, int count, char **out);  


void main(void)
{
    int count, maxlen, i;
    char inpString[]={"Hello#Greatest#Day#Today"};
    char *resultBuf[10];

    //get a count of strings to store
    count = GetCount(inpString, "#", &maxlen);

    for(i=0;i<10;i++)
    {
        resultBuf[i] = calloc(maxlen+1, sizeof(char));  
    }

    //Store strings in arrays
    GetStrings(inpString, "#", count, resultBuf);

    for(i=0;i<count;i++)
    {
        printf("%s\n", resultBuf[i]);
        free(resultBuf[i];
    }             

}
     //Gets count of tokens (delimited strings)
int GetCount(char *in, char *delim, int *m)
{
    char *buf=0;
    char temp1[10]={0};
    char *inStr;
    int count = 0;
    int max = 0, keepMax = 0;
    if(in)
    {

        inStr = calloc(strlen(in)+1, sizeof(char));
        strcpy(inStr, in);
        if(strlen(inStr) > 1)
        {
            count = 0;
            buf = strtok(inStr, delim);
            while(buf)
            {
                strcpy(temp1, buf);
                max = strlen(temp1);
                (max > keepMax)?(keepMax = max):(keepMax == keepMax);
                count++;
                buf = strtok(NULL, delim);
            }
            *m = keepMax;
        }
        free(inStr);
    }
    return count;
}
     //Gets array of strings
int GetStrings(char *in, char *delim, int count, char **out)
{
    char *buf=0;
    char *inStr;
    int i = 0;
    if(in)
    {

        inStr = calloc(strlen(in)+1, sizeof(char));
        strcpy(inStr, in);
        if(strlen(inStr) > 1)
        {
            buf = strtok(inStr, delim);
            while(buf)
            {
                strcpy(out[i], buf);
                buf = strtok(NULL, delim);
                i++;
            }
        }
        free(inStr);
    }
    return 0;
}
于 2013-08-12T18:22:13.307 に答える