C Programming Code Examples C > Strings Code Examples program to trim leading and trailing white spaces from a string 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. Logic to remove leading and trailing white spaces 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 */ #include <stdio.h> #define maxsize 100 // Maximum string size /* Function declaration */ void trim(char * str); int main() { char str[maxsize]; /* 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, j; /* Trim leading white spaces */ index = 0; while(str[index] == ' ' || str[index] == '\t' || str[index] == '\n') { index++; } /* Shift all trailing characters to its left */ j = 0; while(str[j + index] != '\0') { str[j] = str[j + index]; j++; } str[j] = '\0'; // Terminate string with NULL /* Trim trailing white spaces */ j = 0; index = -1; while(str[j] != '\0') { if(str[j] != ' ' && str[j] != '\t' && str[j] != '\n') { index = j; } j++; } /* Mark the next character to last non white space character as NULL */ str[index + 1] = '\0'; }