Prerequisite: Strings
Quick reference
- All functions are in
<string.h>.- All
nvariants of string functions work on only first n characters of the string.- String must always be of size
n+1where n is the number of characters. This is to add the null terminator\0at the end.
1. strlen() – Length
size_t len = strlen("hello"); // 5-
Scans until it meets
'\0'. -
O(n); avoid inside tight loops on big buffers.
2. strcpy() / strncpy() – Copy
char dst[10];
strcpy(dst, "hi"); // copies 'h','i','\0'
strncpy(dst, "hello", 3); // "hel\0..."Rule: Always guarantee
dst≥ src + 1 to prevent buffer overflow.
3. strcat() / strncat() – Append
char msg[16] = "Hi ";
strcat(msg, "Bob"); // "Hi Bob"-
strcatfirst walks to the end (O(n)) then appends. -
Ensure room for new bytes and terminating
\0.
4. strcmp() / strncmp() – Compare
strcmp("abc","abc"); // 0 → equal
strcmp("abc","abd"); // <0
strncmp("abc","abd",2);// 0 (first 2 equal)Return sign indicates lexical order.
5. strchr() & strrchr() – Find a Char
char *p = strchr(cmd, ' '); // first space
p = strrchr(path, '/'); // last slash6. strstr() – Find a Sub‑string
if (strstr(buf, "OK\r\n")) ...Uses a tuned two‑way search in glibc / newlib → near‑linear on average.
7. strpbrk() – First of Any Set
char *p = strpbrk(str, ",;:"); // first delimiter8. strcspn() / strspn() – Span Length
size_t n = strcspn("abc,def", ",");Output
3 (As ',' appears after abc)-
strcspn= count bytes until a char from set appears. -
strspn= count bytes while only chars from set appear.
9. memcpy() / memmove() – Raw Copy
memcpy(dst, src, n); // fastest, undefined if regions overlap
memmove(dst, src, n); // safe when overlapUse when data may contain
'\0'or isn’t a true C‑string.
10. memset() – Fill
This sets all bytes in the specified buffer to a single value.
memset(buf, 0, sizeof(buf)); // Sets all bytes in buf to 011. strtok() / strtok_r() – Tokenise
It performs tokenization of string elements based on the specified delimiter. It carries this out by modifying original string by replacing delimiter with \0.
char s[] = "red,green,blue";
char* tok = strtok(s, ",");
while (tok) {
printf("%s\n", tok);
tok = strtok(NULL, ",");
}Output
red
green
blue-
Writes
'\0'separators into the original buffer. -
Not thread‑safe → use
strtok_r(POSIX) or DIY FSM in bare‑metal.
12. sscanf() / sprintf() – Formatted In/Out
int x; char y[8];
sscanf("12,OK", "%d,%7s", &x, y); // x=12, y="OK"
sprintf(msg, "V=%u mV", adc_mv); // to RAMEmbedded tip: prefer
snprintfto cap output length.