borat borat - 1 month ago 5
C Question

How do I store tokenized strings into arrays in C

In my program I read some text that contains the string "

y'
" and "
y''
" and I want to store that into my array called lhs[100] and the rest of the text goes into rhs[100].

How do I do this? I am stuck on deciding if it works with
strstr()
or
strcpy()
.

#include <stdio.h>
#include <string.h>

int main() {
FILE *fin;
fin = fopen("diffeq.txt", "r");
char line[100];
char split[] = " +-";
char* token;
char lhs[100];
char rhs[100];
int i = 0;

while (fgets(line, sizeof(line), fin) != NULL)
{
for (token = strtok(line, split); token; token = strtok(NULL, split))
{
// I need to find from the token the string "y'" and "y''"
// and store them into array "lhs[100]" and the rest of the
// contents stored into "rhs[100]"
}
}
fclose(fin);
return 0;
}

Answer

This code is working on a sample text. i tested and it works fine. so just you should add read file to text statements. also if you want to add a space between tokens, remove comment sign from //token[j++] = ' ';:

#include <stdio.h>
#include <string.h>
int main() {
    char text[] = "this is a y' sample y'' text y ynot?";
    int len = strlen(text);
    char token[50];
    char lhs[100];
    char rhs[100];
    int state = 0;
    int i, j = 0;
    token[0] = '\0';
    lhs[0] = '\0';
    rhs[0] = '\0';
    printf("\nlen: %d", len);
    for (i = 0; i < len; i++)
        switch (text[i]) {
        case ' ':
        case '+':
        case '-':
            //token[j++] = ' ';
            token[j] = '\0';
            //printf("\ntoken> %s", token);
            // separator is seen, check the token 
            if (state == 2 || state == 3)
                // token is "y'" or "y''"
                strcat(lhs, token);
            else
                // other token detected
                strcat(rhs, token);
            state = 0;
            j = 0;
            break;
        case 'y':
            token[j++] = text[i];
            if (state == 0)
                // first 'y' is detected
                state = 1;
            else
                state = 0;
            break;
        case '\'':
            token[j++] = text[i];
            if (state == 1)
                // we had token=="y" so now we have token=="y'"
                state = 2;
            else if (state == 2)
                // we had token=="y'" so now we have token=="y''"
                state = 3;
            else state = 0;
            break;
        default:
            token[j++] = text[i];
            state = 0;
            break;
        }
    // check token detection condition for last token
    if (state == 2 || state == 3)
        strcat(lhs, token);
    else
        strcat(rhs, token);

        printf("\n\nlhs> %s\nrhs> %s", lhs, rhs);
}
Comments