Last active
August 13, 2019 11:02
-
-
Save gustavorv86/130ad4722cc7c3bd86731683429cc721 to your computer and use it in GitHub Desktop.
Function to trimmed string in ANSI C 11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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