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.
Example
Input
Input string: " Lots of leading and trailing spaces. "
Output
String after removing leading and trailing white spaces: "Lots of leading and trailing spaces."
Required knowledge
Basic C programming, Loop, String, Function
Must know – Program to remove element from array
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.
Read more –
Program to trim leading and trailing white spaces
/**
* 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: Lots of white spaces. String before trimming white space: ' Lots of white spaces. ' String after trimming white space: 'Lots of white spaces.'
Happy coding 😉
Recommended posts
- String programming exercises index.
- C program to remove extra blank spaces from a string.
- C program to search all occurrences of a character in a string.
- C program to search all occurrences of a word in a string.
- C program to count frequency of each character in a string.
- C program to remove all occurrences of a character from a string.
- C program to remove all repeated characters from a string.