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

//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.