C - Trim Leading and Trailing Whitespaces using C Program.
In this code snippet, we will learn how to trim leading and trailing whitespaces using c program. For example if you enter string " Hello World! ", after trimming output string will be "Hello World!" Program will be removed leading and trailing whitespaces from the string.
C Code Snippets - Trim Leading and Trailing Whitespaces
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | #include <stdio.h>
#include <string.h>
#include <ctype.h>
void trimString( char * str, char * target)
{
char *str1;
char *last;
while ( isspace (*str)) str++;
printf ( "string2: %s\n" ,str);
if (*str == 0)
return ;
last = str + strlen (str) - 1;
while (last > str && isspace (*last)) last--;
*(last+1) = 0;
strcpy (target,str);
}
int main()
{
char str[100]={0},targetString[100]={0};
printf ( "Enter a string: " );
fgets (str, 100, stdin);
trimString(str,targetString);
printf ( "Trimmed String is: %s#\n" ,targetString);
return 0;
}
|
Enter a string: Hello World!
string2: Hello World!
Trimmed String is: Hello World!