Search code examples
carrayscharsub-array

How to extract a sub char array from a char array


I am trying to create a mapping in which I compare 5 char and match them with a case. My problem is the syntax of char arrays and maybe there is an easier way to extract sub arrays.

My general idea is:

char str[80];
char tempStr[5]="";
int i=0;

for(i=0; i<4; i++){
   strcat(tempStr,str[i]);


}
// match tempStr to cases
// go back to loop through for the next tempStr

Example input:

"Iliveon123streetUnitedStatesOfAmericaSSS"

Each time I loop through I would like to extract a subarray of

"Ilive"
"on123"
"stree"
"tUnit"
"edSta"
"tesOf"
"Ameri"
"caSSS"

and compare this temp string


Solution

  • There is no reason to set up you iteration in a for loop. A better approach is simply to loop while there are still characters to output that have not yet been output. Consider the strlen of your input string that you will break into blocksize chunks and output each iteration. When done outputting the block, simply subtract the blocksize output from the length to determine the number of characters that remain. Continue until less than blocksize characters or no characters remain.

    If less than a full blocksize of characters remain to be output on your final iteration, just update your blocksize to the remaining length and output that number of chars.

    There is no need to scan for the end of the string using strcpy, etc.. Your blocksize determines the number of characters in each substring, so you can simply memcpy you characters, adding the nul-terminating character at substring[blksz] and then outputting the resulting string (with escaped quotes as you show)

    A minimal example using your input could be:

    #include <stdio.h>
    #include <string.h>
    
    #define BLKSZ 5
    
    int main (void) {
    
        char str[] = "Iliveon123streetUnitedStatesOfAmericaSSS",
            blk[BLKSZ + 1];         /* storage for each substring */
        size_t len = strlen (str),  /* length of str */
            blksz = BLKSZ,          /* initial blocksize */
            n = 0;                  /* block counter */
    
        while (len) {           /* while chars remain to copy */
            memcpy (blk, str + n++ * BLKSZ, blksz); /* copy blocksize chars */
            blk[blksz] = 0;     /* nul-terminate block */
            printf ("\"%s\"\n", blk);   /* output block */
            len -= blksz;       /* subtract blocksize from len */
            if (len < blksz)    /* less than blocksize remains, blksz is len */
                blksz = len;
        }
    }
    

    Example Use/Output

    $ ./bin/strsubstr
    "Ilive"
    "on123"
    "stree"
    "tUnit"
    "edSta"
    "tesOf"
    "Ameri"
    "caSSS"
    

    Look things over and let me know if you have further questions.