Definition
📌 Strings
C has no built-in string type.
Syntax
syntax
char str[] = "text";
#include <string.h>
strlen(str);
strcpy(dest, src);
strcat(dest, src);Example
c
#include <stdio.h>
#include <string.h>
int main() {
char name[20] = "CodeyHub";
printf("Name: %s\n", name);
printf("Length: %lu\n", strlen(name));
return 0;
}Output
outputName: CodeyHub
Length: 8
Important Points
- A C string is a
chararray ending with'\0'(null terminator). strlen()returns the length excluding the null terminator.- Always leave enough room in the array for the null terminator when declaring a size.
strcmp(a, b)compares two strings and returns 0 if they are equal.
Common Mistakes
- Declaring an array too small to hold the string plus its null terminator.
- Comparing strings with
==instead ofstrcmp()— that only compares memory addresses. - Forgetting to
#include <string.h>before using string functions.
Interview Tip
🎯 Before your interview
A very common interview question: "why can't you compare C strings with ==?" — because that compares pointer addresses, not string contents; use
strcmp instead.
