Standard Library: string.h
The string.h header provides functions for manipulating C strings (null-terminated character arrays).
---
String Length
#include <string.h>
char s[] = "Hello";
int len = strlen(s); /* 5 — does not count \0 */
---
String Copy
char dest[20];
char src[] = "World";
strcpy(dest, src); /* copies src to dest */
strncpy(dest, src, 3); /* copies at most 3 chars */
printf("%s\n", dest); /* Wor */
---
String Concatenation
char s1[30] = "Hello";
char s2[] = " World";
strcat(s1, s2); /* s1 = "Hello World" */
strncat(s1, s2, 3); /* appends at most 3 chars */
---
String Comparison
strcmp(s1, s2) /* 0 if equal, <0 if s1 < s2, >0 if s1 > s2 */
strncmp(s1, s2, n) /* compare first n characters */
strcmpi(s1, s2) /* case-insensitive compare (non-standard) */
---
String Search
char *p;
p = strchr("Hello World", 'o'); /* pointer to first 'o' */
p = strrchr("Hello World", 'o'); /* pointer to last 'o' */
p = strstr("Hello World", "World"); /* pointer to "World" */
---
String Transformation
strupr(str); /* convert to uppercase (non-standard) */
strlwr(str); /* convert to lowercase (non-standard) */
strrev(str); /* reverse string (non-standard) */
Portable alternatives:
#include <ctype.h>
for (int i = 0; str[i]; i++) {
str[i] = toupper(str[i]); /* ANSI-portable uppercase */
}
---
Memory Functions (also in string.h)
| Function | Description |
|---|---|
memcpy(dest, src, n) | Copy n bytes |
memmove(dest, src, n) | Copy n bytes (handles overlap) |
memset(ptr, val, n) | Fill n bytes with val |
memcmp(s1, s2, n) | Compare n bytes |
char buf[10];
memset(buf, 0, sizeof(buf)); /* zero out buffer */
---
Common String Programs
/* Check if palindrome */
#include <stdio.h>
#include <string.h>
int isPalindrome(char s[]) {
int n = strlen(s);
for (int i = 0; i < n/2; i++) {
if (s[i] != s[n-1-i]) return 0;
}
return 1;
}
int main() {
printf("%d\n", isPalindrome("madam")); /* 1 */
printf("%d\n", isPalindrome("hello")); /* 0 */
}