You can't use =, + or == on strings in C. Instead, use the functions in <string.h>:
| Function | What it does |
|---|---|
strlen(s) | How many characters (not counting '\0') |
strcpy(dest, src) | Copy src into dest |
strcat(dest, src) | Add src to the end of dest |
strcmp(a, b) | Compare: 0 if they are equal |
strlen: the length
#include <stdio.h>
#include <string.h>
int main() {
char word[20] = "banana";
printf("%s has %d letters\n", word, (int) strlen(word));
return 0;
}Output
banana has 6 letters
strcpy and strcat: copy and join
#include <stdio.h>
#include <string.h>
int main() {
char full[50];
strcpy(full, "Hello");
strcat(full, ", ");
strcat(full, "World");
printf("%s\n", full);
return 0;
}Output
Hello, World
Common mistake: Making the destination too small.
strcpyandstrcatdon't check the size – if the text doesn't fit, they write past the end of the array. Always make the array big enough.
strcmp: are two strings equal?
strcmp returns 0 when the two strings are the same. (A negative or positive number means the first one comes before or after the other in dictionary order.)
#include <stdio.h>
#include <string.h>
int main() {
char password[20];
scanf("%s", password);
if (strcmp(password, "open123") == 0) {
printf("Access granted\n");
} else {
printf("Wrong password\n");
}
return 0;
}Input (what the user types)
open123
Output
Access granted
Common mistake: Writing
if (password == "open123"). That compares memory addresses, not the text, and is almost always false. Usestrcmp.
Looping over a string
Go through a string letter by letter until you reach '\0':
#include <stdio.h>
int main() {
char text[30] = "hello world";
int vowels = 0;
for (int i = 0; text[i] != '\0'; i++) {
char c = text[i];
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
}
}
printf("Vowels: %d\n", vowels);
return 0;
}Output
Vowels: 3