I'm learning C after 12 years of web dev and I want to learn something new without web involving and more low level.
My goal is to read id3v1 tag (for now) from mp3 file and I need to trim space and I would like to have some reviews about my code and the best approach to use ltrim and rtrim, it's better to call ltrim and rtrim in trim_all or having a trim function whitout calling ltrim and rtrim but with it's own implementation like trim function?
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void trim(char *str) {
if (str == NULL || str[0] == '\0') return;
int start = 0;
size_t end = strlen(str) - 1;
while (isspace(str[start])) start++;
while (end > start && isspace(str[end])) end--;
size_t new_length = end - start + 1;
memmove(str, str + start, new_length);
str[new_length] = '\0';
}
void ltrim(char *str) {
if (str == NULL || str[0] == '\0') return;
int start = 0;
const size_t end = strlen(str);
while (isspace(str[start])) start++;
size_t new_length = end - start + 1;
memmove(str, str + start, new_length);
}
void rtrim(char *str) {
if (str == NULL || str[0] == '\0') return;
size_t end = strlen(str) - 1;
while (isspace(str[end])) end--;
size_t new_length = end + 1;
str[new_length] = '\0';
}
void trim_all(char *str) {
ltrim(str);
rtrim(str);
}
int main(void) {
char str[] = " Hello, World! ";
trim(str);
printf("%s\n", str);
char str2[] = " Hello, World! ";
ltrim(str2);
printf("%s\n", str2);
char str3[] = " Hello, World! ";
rtrim(str3);
printf("%s\n", str3);
char str4[] = " Hello, World! ";
trim_all(str4);
printf("%s\n", str4);
return 0;
}