Home > Software design >  How do I create an array based off an existing array where each element of the new array copies the
How do I create an array based off an existing array where each element of the new array copies the

Time:01-12

I have an array of strings read from a file. I'd like to take each string in the existing array and copy it to a new array unit the first instance of a tab character, and then move to the next element in the array.

What would be the best way to do this?

Thanks

CodePudding user response:

You can use standard C function strchr. For example if you have two character arrays like

char s1[12] = "Hello\tWorld";
char s2[12];

then you can write

char *p = strchr( s1, '\t' );

if ( p != NULL )
{
    memcpy( s2, s1, p - s1 );
    s2[p - s1] = '\0';
}
else
{
    strcpy( s2, s1 );
}

For two dimensional arrays you can do the same in a loop.

CodePudding user response:

You could create a function until_tabs that takes an array of strings and the array's length. Then we allocate a same sized array of char pointers and iterate over the original array.

For each string input we can use strchr to look for a tab. If it's absent, just duplicate the string with strdup. Otherwise allocate an adequately sized buffer for the new string and copy everything before '\t' into it with strncpy.

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

char **until_tabs(char **strings, size_t n) {
    char **result = malloc(sizeof(char *) * n);
    for (size_t i = 0; i < n; i  ) {
        char *tab = strchr(strings[i], '\t');
        if (!tab) {
            result[i] = strdup(strings[i]);
            continue;
        }

        size_t size = tab-strings[i];
        result[i] = malloc(size 1);
        strncpy(result[i], strings[i], size);
        result[i][size] = '\0';
    }

    return result;
}

int main(void) {
    char *arr[] = {"hello", "world", "foo\tbar"};
    char **arr2 = until_tabs(arr, 3);

    for (size_t i = 0; i < 3; i  ) {
        printf("%s\n", arr2[i]);
    }

    return 0;
}

Output:

hello
world
foo
  • Related