Skip to content

Instantly share code, notes, and snippets.

@TrickSumo
Last active July 12, 2018 10:16
Show Gist options
  • Save TrickSumo/653e6f984c21bc38db998e26b5682af5 to your computer and use it in GitHub Desktop.
Save TrickSumo/653e6f984c21bc38db998e26b5682af5 to your computer and use it in GitHub Desktop.
Program to remove leading and trailing spaces in C [rtrim(), ltrim() and trim()]
#include <stdio.h>
#include <string.h>
/* Originally posted at https://www.tricksumo.com/string-trim-functions-c/
Author Name:- Rishi Tiwari
Site URL:- TrickSumo.com */
char* rtrim();
char* ltrim();
char* trim();
int main() {
char str1[30]="First ";
char str2[30]=" Second";
char str3[30]=" Third ";
printf("[%s]\n",rtrim(str1));
printf("[%s]\n",ltrim(str2));
printf("[%s]\n",trim(str3));
return 0;
}
// Rtrim () starts from here.
char* rtrim(char a[30])
{
int i=strlen(a)-1;
// We are not considering next line character '\n' because it is already removed.
for (i; a[i]==' '|| a[i]=='\t'; i--) {
a[i]='\0'; }
return a; }
//Ltrim() starts from here.
char* ltrim(char b[30]) {
int i=0, j=0;
char ltrim[30]="\0";
for(i; b[i]==' ' || b[i]=='\t'; i++);
while (b[i]!='\0')
{
ltrim[j]=b[i];
i++;
j++; }
strcpy(b,ltrim);
return b;
}
// Trim() starts from here.
char* trim(char c[30])
{
rtrim(c);
ltrim(c);
return c;
}
@TrickSumo
Copy link
Author

TrickSumo commented Jul 12, 2018

Hi

This is my first gist on github.

Program originally published at TrickSumo C Blog.

Feel free to ask anything or suggest improvements.

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment