C program to trim leading and trailing white spaces from a string

Write a C program to trim both leading and trailing white space characters in a string using loop. How to remove both leading and trailing white space characters in a string using loop in C programming. Logic to delete all leading and trailing white space characters from a given string in C.

Required knowledge

Basic C programming, C if-else, C for loop, Array, functions, Strings

Logic to remove leading and trailing white spaces

In my previous posts, I already explained how to remove leading as well as trailing white space characters from a given string. Here in this program we will combine the logic of both in a single program.

C program to trim both leading and trailing white space characters from a string



 
/**
 * C program to trim both leading and trailing white space characters from a string
 */

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

/* Function declaration */
void trim(char * str);


int main()
{
    char str[MAX_SIZE];

    /* Input string from user */
    printf("Enter any string: ");
    gets(str);

    printf("\nString before trimming white space: \n'%s'", str);

    trim(str);

    printf("\n\nString after trimming white space: \n'%s'", str);

    return 0;
}


/**
 * Remove leading and trailing white space characters
 */
void trim(char * str)
{
    int index, i;

    /*
     * Trim leading white spaces
     */
    index = 0;
    while(str[index] == ' ' || str[index] == '\t' || str[index] == '\n')
    {
        index++;
    }

    /* Shift all trailing characters to its left */
    i = 0;
    while(str[i + index] != '\0')
    {
        str[i] = str[i + index];
        i++;
    }
    str[i] = '\0'; // Terminate string with NULL


    /*
     * Trim trailing white spaces
     */
    i = 0;
    index = -1;
    while(str[i] != '\0')
    {
        if(str[i] != ' ' && str[i] != '\t' && str[i] != '\n')
        {
            index = i;
        }

        i++;
    }

    /* Mark the next character to last non white space character as NULL */
    str[index + 1] = '\0';
}



Output:

Enter any string: I love c programming
String before trimming white space:
'I love c programming'
String after trimming white space:
'I love c programming'
Process returned 0 (0x0) execution time : 10.027 s



Instagram