Programs & Examples
Strings · Study material
Count letters, digits, spaces and other characters
The ctype functions classify each character; cast to unsigned char first.
#include <stdio.h>
#include <ctype.h>
int main(void) {
const char *s = "C23 adds nullptr & typeof!";
int letters = 0, digits = 0, spaces = 0, others = 0;
for (const char *p = s; *p; p++) {
unsigned char c = (unsigned char) *p;
if (isalpha(c)) letters++;
else if (isdigit(c)) digits++;
else if (isspace(c)) spaces++;
else others++;
}
printf("letters %d, digits %d, spaces %d, others %d\n", letters, digits, spaces, others);
return 0;
}
letters 18, digits 2, spaces 4, others 2
Sort an array of strings with qsort()
The array holds const char * values, so the comparator receives pointers to those pointers – dereference once, then call strcmp().
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int cmp_str(const void *a, const void *b) {
/* qsort passes pointers to the elements, and each element is a char pointer */
return strcmp(*(const char *const *) a, *(const char *const *) b);
}
int main(void) {
const char *langs[] = {"Python", "C", "Java", "Rust", "Go"};
qsort(langs, 5, sizeof langs[0], cmp_str);
for (int i = 0; i < 5; i++)
printf("%s ", langs[i]);
printf("\n");
return 0;
}
C Go Java Python Rust
Convert a sentence to title case
Uppercase the first letter after each space, in place.
#include <stdio.h>
#include <ctype.h>
int main(void) {
char s[] = "learn c the modern way";
int start = 1;
for (char *p = s; *p; p++) {
if (*p == ' ') {
start = 1;
} else if (start) {
*p = (char) toupper((unsigned char) *p);
start = 0;
}
}
printf("%s\n", s);
return 0;
}
Learn C The Modern Way
Join parts into a path with snprintf()
Append with snprintf(out + used, sizeof out - used, …): each call knows exactly how much room is left.
#include <stdio.h>
int main(void) {
const char *parts[] = {"home", "user", "projects"};
char out[64];
size_t used = 0;
out[0] = '\0';
for (int i = 0; i < 3 && used < sizeof out; i++)
used += snprintf(out + used, sizeof out - used, "/%s", parts[i]);
printf("%s (%zu chars)\n", out, used);
return 0;
}
/home/user/projects (19 chars)