D
David RF
Hi, anybody knows a better way to (right-left) trim a string?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* Trim (right-left) and returns a new allocated string or NULL */
char *sstrip(const char *s);
char *sstrip(const char *s)
{
char *value = NULL;
size_t len;
if (s) {
while (*s && isspace(*s)) s++;
for (len = strlen(s); isspace(s[len - 1]); len--);
value = malloc(len + 1);
if (!value) {
fprintf(stderr, "%s\n", "Buy more RAM!!");
exit(0);
}
strncpy(value, s, len);
value[len] = '\0';
}
return value;
}
int main(void)
{
char *s;
s = sstrip("test");
printf("<%s>\n", s);
if (s) free(s);
s = sstrip(" test ");
printf("<%s>\n", s);
if (s) free(s);
s = sstrip("test ");
printf("<%s>\n", s);
if (s) free(s);
s = sstrip(" test");
printf("<%s>\n", s);
if (s) free(s);
s = sstrip("");
printf("<%s>\n", s);
if (s) free(s);
s = sstrip(NULL);
printf("<%s>\n", s);
if (s) free(s);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* Trim (right-left) and returns a new allocated string or NULL */
char *sstrip(const char *s);
char *sstrip(const char *s)
{
char *value = NULL;
size_t len;
if (s) {
while (*s && isspace(*s)) s++;
for (len = strlen(s); isspace(s[len - 1]); len--);
value = malloc(len + 1);
if (!value) {
fprintf(stderr, "%s\n", "Buy more RAM!!");
exit(0);
}
strncpy(value, s, len);
value[len] = '\0';
}
return value;
}
int main(void)
{
char *s;
s = sstrip("test");
printf("<%s>\n", s);
if (s) free(s);
s = sstrip(" test ");
printf("<%s>\n", s);
if (s) free(s);
s = sstrip("test ");
printf("<%s>\n", s);
if (s) free(s);
s = sstrip(" test");
printf("<%s>\n", s);
if (s) free(s);
s = sstrip("");
printf("<%s>\n", s);
if (s) free(s);
s = sstrip(NULL);
printf("<%s>\n", s);
if (s) free(s);
return 0;
}