C - Trim Leading and Trailing Whitespaces using C Program.


IncludeHelp 30 July 2016

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
//C - Trim Leading and Trailing Whitespaces using C Program.
 
#include <stdio.h>
#include <string.h>
#include <ctype.h>
 
/****************************************
    function    : trimString
    Description : Remove leading and trailing
                  whitespaces
    Author      : IncludeHelp
*****************************************/
void trimString(char* str, char* target)
{
    char *str1;
    char *last;
 
    /*trim starting (leading) white space*/
    while(isspace(*str)) str++;
        printf("string2: %s\n",str);
 
     if(*str == 0)
        return;
 
      /*trim last (trailing) white space*/
      last = str + strlen(str) - 1;
      while(last > str && isspace(*last)) last--;
 
      /*end null after string*/
      *(last+1) = 0;
      strcpy(target,str);    
}
 
int main()
{
    char str[100]={0},targetString[100]={0};
     
    printf("Enter a string: ");
    fgets (str, 100, stdin);
     
    //trim string removing leading and trailing spaces
    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!



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.