ADVERTISEMENT
ADVERTISEMENT

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!

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.