Trim both leading and trailing white space characters from given string
C program to trim both leading and trailing white space characters from given string.
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 50
void main()
{
char str[MAX];
int i, pos;
printf("Enter the string\t:");
gets(str);
printf("\nOriginal String\t:'%s'",str);
// learding white spaces
pos = 0;
while(str[pos]==' ' || str[pos]=='\t')
{
pos++;
}
if(pos != 0)
{
i = 0;
while(str[i+pos]!='\0')
{
str[i] = str[i+pos];
i++;
}
str[i] = '\0';
}
//trailing white spaces
pos = -1;
i = 0;
while(str[i] != '\0')
{
if(str[i]!=' ' && str[i]!='\t')
{
pos = i;
}
i++;
}
str[pos + 1] = '\0';
printf("\nModified string\t:'%s'",str);
getch();
}
Output
Enter the string : welcome to coursecrux.com
Original String :' welcome to coursecrux.com '
Modified string :'welcome to coursecrux.com'