Skip to content

Instantly share code, notes, and snippets.

@gustavorv86
Last active August 13, 2019 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gustavorv86/130ad4722cc7c3bd86731683429cc721 to your computer and use it in GitHub Desktop.
Save gustavorv86/130ad4722cc7c3bd86731683429cc721 to your computer and use it in GitHub Desktop.
Function to trimmed string in ANSI C 11
// COMPILE: gcc -std=c11 -Wall -Wextra c_string_trim.c -o string_trim
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
char * string_trim(char * string) {
int s_size = strlen(string);
int left_spaces = 0;
for(int i=0; i<s_size; i++) {
if(isspace(string[i])) {
left_spaces++;
} else {
break;
}
}
int right_spaces = 0;
for(int i=(s_size-1); i>=0; i--) {
if(isspace(string[i])) {
right_spaces++;
} else {
break;
}
}
char * new_ptr = calloc(s_size-left_spaces-right_spaces+1, sizeof(char));
int count = 0;
for(int i=left_spaces; i<(s_size-right_spaces); i++) {
new_ptr[count++] = string[i];
}
new_ptr[count] = '\0';
return new_ptr;
}
int main() {
char string[] = "\t\t Hello World \t\r\n";
char * string_trimmed = string_trim(string);
printf("'%s'\n", string_trimmed);
free(string_trimmed);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment