Search code examples
cstringperformancememorydelimiter

How to store a substring given a delimiter in C


Let's say I have a series of data that's in this form:

"SomethingIDontCareAbout : SomethingICareAbout"

where the part after the ":" can vary in length of course.

The goal here is only storing the "SomethingICareAbout" substring efficiently. I made this function but the problem is that I'm storing both substrings,so it seems like a waste of memory. Any help to reduce to the time/space complexity?

char** ExtractKey(char* S)           
{
    int n = strlen(S);
    int count = 0, i = 0, j = 0;
    for(i = 0; i < n; i++)
    {
        if(S[i] == ':')
            break;
        
        count++;
    }
    char** T = (char**)malloc(2 * sizeof(char*));

    T[0] = (char*)malloc((count + 1)  * sizeof(char));
    T[1] = (char*)malloc((n - count) * sizeof(char));

    for(i = 0; i < count; i++)                          // inefficient ? cus we won't need T[0] [j]
    {
        T[0][j] = S[i];
        j++;
    }
    T[0][j+1] = '\0';
    j = 0;
    for(i = count + 1; i < n; i++)
    {
        T[1][j] = S[i];
        j++;
    }
    T[1][j+1] = '\0';
    return T;
}

Solution

  • There is no reason to invent a search for a character in a string, or a copy of a string.

    If the input data will live long enough for you to use the "value" part, just return a pointer to the value:

    char* ExtractKey(char* S)           
    {
      return strchr(S, ':');
    }
    

    If it doesn't, or if you for some reason need a separate copy:

    char* ExtractKey(char* S)           
    {
      return strdup(strchr(S, ':'));
    }