# strtrim.c -rw-r--r-- 597 bytes View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

/*
 * Removes trailing and leading whitespace from the string. Returns NULL on
 * allocation failure. The result must be freed by the caller.
 */
char *strtrim(char *old) {
	size_t len = strlen(old);

	size_t start = 0;
	size_t end = len - 1;

	while (start < len - 1 && isspace(old[start])) start++;
	while (end >= start && isspace(old[end])) end--;

	size_t newlen = end - start + 1;

	char *new = calloc(newlen + 1, sizeof(char));
	if (new == NULL) return NULL;

	memcpy(new, old + start, newlen);
	new[newlen] = '\0';

	return new;
}
# testcases.c -rw-r--r-- 658 bytes View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

char *strtrim(char *);

int
main()
{
	char *new1 = strtrim("   Some things\t");
	assert(new1 != NULL);
	printf("[%s]\n", new1); // [Some things]
	free(new1);

	char *new2 = strtrim("");
	assert(new2 != NULL);
	printf("[%s]\n", new2); // []
	free(new2);

	char *new3 = strtrim("     \t");
	assert(new3 != NULL);
	printf("[%s]\n", new3); // []
	free(new3);

	char *new4 = strtrim("hello world\t  ");
	assert(new4 != NULL);
	printf("[%s]\n", new4); // [hello world]
	free(new4);

	char *new5 = strtrim("\t  hello world");
	assert(new5 != NULL);
	printf("[%s]\n", new5); // [hello world]
	free(new5);
}