Step 2 of 6
strlen and friends
Since strings are arrays, you can't combine or copy them with = or + like in other languages. char a[10]; a = "hi"; doesn't compile: arrays can't be assigned. Instead, the standard library <string.h> provides functions:
| Function | What it does |
|---|---|
strlen(s) |
counts characters before the '\0' |
strcpy(dst, src) |
copies src into dst, including the terminator |
strcat(dst, src) |
appends src to the end of the text already in dst |
strcmp(a, b) |
compares two strings (next steps) |
#include <stdio.h>
#include <string.h>
int main(void) {
char greeting[40];
strcpy(greeting, "Hello");
strcat(greeting, ", ");
strcat(greeting, "Ada");
printf("%s (%zu chars)\n", greeting, strlen(greeting));
return 0;
}
Hello, Ada (10 chars)
The destination must be big enough
strcpy and strcat don't know how big dst is. They copy until they reach the source's terminator, and if dst is too small they write past its end: a buffer overflow. Always size the destination for the longest possible result, plus one for the '\0'. Here greeting has room for 40, and we use 11.
For text built from several pieces, snprintf is often safer: it works like printf but writes into an array and never writes more than the size you give it:
snprintf(greeting, sizeof greeting, "%s, %s", "Hello", "Ada");
strlen vs sizeof
strlen counts the characters of text currently stored (10 here). sizeof greeting is the size of the whole array (40), no matter what's in it.
More of <string.h>
strncpy(dst, src, n)looks like a safestrcpy, but whensrchasnor more characters it does not add the'\0', so the result isn't a string. Prefersnprintf.strchr(s, c)andstrstr(s, sub)find a character or a substring. They return a pointer to it, orNULLif it isn't there (pointers are the next module).strtoksplits a string on separators, but it writes'\0's into your string and remembers its position in a hidden variable, so it can't work on a string literal or on two strings at once.memset,memcpyandmemmovework on raw bytes of any type.memcpymust not be used when the source and destination overlap;memmovehandles overlap correctly.
Your turn: read two words and print them joined with a - between, followed by the total length. Input de dust2 prints de-dust2 8.