Coding Techniques
Strings · Study material
Frequency table with int[256]
Count characters with one array indexed by the byte value. It solves anagrams, first-unique-character and most-frequent-character problems in O(n).
#include <stdio.h>
int main(void) {
const char *s = "mississippi";
int count[256] = {0}; /* one counter per byte value */
for (const char *p = s; *p; p++)
count[(unsigned char) *p]++; /* the cast keeps the index 0..255 */
int best = 0;
for (int c = 1; c < 256; c++)
if (count[c] > count[best])
best = c;
printf("most frequent: '%c' (%d times)\n", best, count[best]);
return 0;
}
most frequent: 'i' (4 times)
The (unsigned char) cast matters: a negative char would index before the array.
In-place filtering with a read and a write pointer
To delete characters without a second buffer, read with one pointer and write with another that only moves when a character is kept. End with a new terminator.
#include <stdio.h>
void remove_spaces(char *s) {
char *w = s; /* write pointer */
for (const char *r = s; *r; r++) /* read pointer */
if (*r != ' ')
*w++ = *r;
*w = '\0'; /* end the shorter string */
}
int main(void) {
char s[] = "a b c d";
remove_spaces(s);
printf("%s\n", s);
return 0;
}
abcd
Bounded copies and joins
Prefer one snprintf() over chains of strcpy() and strcat(): it knows the buffer size, always terminates, and reports truncation.
char full[64];
int n = snprintf(full, sizeof full, "%s %s", first, last);
if (n < 0 || (size_t) n >= sizeof full) {
/* the name did not fit: handle it instead of silently cutting it */
}When you must use strncpy(d, s, n), add d[n - 1] = '\0'; yourself.
Parsing numbers with strtol()
atoi() cannot report errors: "abc" and "0" both give 0. strtol() tells you where parsing stopped and sets errno on overflow.
char *end;
errno = 0;
long v = strtol(text, &end, 10);
if (end == text) puts("no digits");
else if (*end != '\0') puts("extra characters after the number");
else if (errno == ERANGE) puts("out of range"); Safe string habits
- Size buffers as length + 1, and use
sizeof buf, not a repeated number. - Read lines with
fgets(); nevergets(). - Use
%15s(a width) if you must usescanf("%s"). - Point to literals with
const char *. - Compare with
strcmp(); teststrchr()/strstr()results for NULL. - Pass
(unsigned char) cto ctype functions.