Example:
Input string: " Lots of leading and trailing spaces. "
Output string: "Lots of leading and trailing spaces."
Required knowledge
Basic C programming, Loop, String, FunctionBefore moving on to this program if you haven't done with previous program on trimming spaces, it is recommended to go though both of them how to trim leading spaces and trailing spaces.
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 size of the string /* Function declaration */ void trimT(char * string); int main() { char string[MAX_SIZE]; /* Reads string from user */ printf("Enter any string: "); gets(string); printf("String before trimming whitespace: \"%s\"\n", string); trim(string); printf("String after trimming whitespace: \"%s\"\n", string); return 0; } /** * Remove leading and trailing whitespace characters from a string */ void trim(char * string) { int lastIndex, lastSpaceIndex, i, j; /* * Trims leading white spaces */ lastSpaceIndex = 0; /* Finds the last index of whitespace character */ while(string[lastSpaceIndex] == ' ' || string[lastSpaceIndex] == '\t' || string[lastSpaceIndex] == '\n') { lastSpaceIndex++; } /* Shits all trailing characters to its left */ i = 0; while(string[i + lastSpaceIndex] != '\0') { string[i] = string[i + lastSpaceIndex]; i++; } string[i] = '\0'; //Make sure that string is NULL terminated /* * Trims trailing white spaces */ /* Finds the last non white space character */ i = 0; while(string[i] != '\0') { if(string[i] != ' ' && string[i] != '\t' && string[i] != '\n') { lastIndex = i; } i++; } /* Mark the next character to last non white space character as NULL */ string[lastIndex + 1] = '\0'; }
Output
Enter any string: Lots of white spaces.
String before trimming whitespace: " Lots of white spaces. "
String after trimming whitespace: "Lots of white spaces."
String before trimming whitespace: " Lots of white spaces. "
String after trimming whitespace: "Lots of white spaces."
Happy coding ;)
You may also like
- String programming exercises index.
- C program to remove extra blank spaces from a string.
- C program to toggle case of each character of a string.
- C program to check whether a string is palindrome or not.
- 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 find highest frequency character 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.