Search code examples
cstringtrim

How to improve this trim-half-string algorithm?


I have simple algorithm that clean the whitespace from half string until end. Here it is:

char a[] = "abc         "; /* The string to string to trim. */
printf("orginal [%s]\n", a);
char * org = strdup(a); /* duplicate the orginal string */
char * half_str = org + strlen(a) / 2; /* Get the half of string. */
strrev(half_str); /* reverse the string */
char * phs = half_str; /* Point to half_string */
char * news = malloc(strlen(half_str) + 1); /* The new string, without spaces. */
char * ptonews = news; /*Pointer to new string */

while(*phs) 
{
    /* if it's not whitespace like( ,\f,\r,\t,\v,\n) then concat to new string. */
    if(!isspace(*phs)) {
        *ptonews ++= *phs;      
    }
    phs ++;
}

/*Put the 0-terminator into new string. */
*phs ++ = '\0'; 

/* Replace the half_str with the newstring */
strcpy(half_str, news);

printf("new string [%s]\n", org);

it works fine. the output is:

orginal [abc        ]
new string [abc]

But the C code is a bit slow. How can I improve it?


Solution

  • You're doing a lot of unnecessary allocation. Try something like this:

    char a[] = "abc     ";
    printf( "original [%s]\n", a);
    int halfTrimmed = strlen(a)/2 + 1;
    for( ; halfTrimmed>0; halfTrimmed-- )
        if( !isspace(a[halfTrimmed-1]) ) break;
    char* news = malloc( halfTrimmed+1 );
    strncpy( news, a, halfTrimmed );
    printf( "new string [%s]\n", news );
    

    In words, this algorithm finds the index of half the string (halfTrimmed), then starts looking at each character, starting at that index, until it finds the first non-space index. It then copies from the beginning of the original string to the last non-space index into a new string, and you're done.