Trim spaces from a string (C/C++)

/* filename: trim.c
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

/** This function will trim a string by eliminating the spaces from
 * the start and the end of the string.
 */
void trim(char *s)
{
    int origLen, len;
    char *sCopy;
    int start, end;

    origLen = strlen(s);
    sCopy = strdup(s);
    if (sCopy != NULL) {
        len = strlen(sCopy);
        for (start=0; start<len; start++) {
            if (!isspace(sCopy[start])) {
                break;
            }
        }

        for (end=len-1; end >= 0; end--) {
            if (!isspace(sCopy[end])) {
                break;
            }
        }

        sCopy[end+1] = '\0';
        strcpy (s, &(sCopy[start]));
        free(sCopy);
    }
}

/* Compile:
 *   g++ -o trim trim.c
 * Test
 *   ./trim "    test string "
 *   String before trim: {    test string }
 *   String  after trim: {test string}
 */
int main (int argc, char *argv[])
{
    char str[1024];
    if (argc <= 1) {
        printf ("Usage: %s <string>\n", argv[0]);
        return -1;
    }
    strcpy (str, argv[1]);
    printf ("String before trim: {%s}\n",argv[1]);
    trim(str);
    printf ("String  after trim: {%s}\n",str);
    return (0);
}

Leave a Reply