Names, cities, passwords and messages are all text. Most languages have a built-in string type for text. C does not. In C, a string is simply an array of char with a special character at the end that marks where the text stops.
This page explains how strings are stored, how to declare them, how to read them from the user safely and how to use the common string.h functions. Every program shows its output. You should know arrays in C before reading this.
How C stores a string: the null terminator
When you write char name[] = "Ravi";, C stores five characters, not four:
Index: [0] [1] [2] [3] [4]
+-----+-----+-----+-----+-----+
name: | 'R' | 'a' | 'v' | 'i' | '\0'|
+-----+-----+-----+-----+-----+
The last one, '\0', is the null character (its code is 0). It is added automatically when you use double quotes. Every string function in C reads characters until it reaches '\0'. Without it, a function would keep reading whatever memory comes next.
#include <stdio.h>
#include <string.h>
int main(void) {
char name[] = "Ravi";
printf("Name: %s\n", name);
printf("strlen: %zu\n", strlen(name));
printf("sizeof: %zu\n", sizeof(name));
printf("Last char code: %d\n", name[4]);
return 0;
}
Output:
Name: Ravi
strlen: 4
sizeof: 5
Last char code: 0
strlen counts the letters before '\0'. sizeof counts every byte in the array, including '\0'.
Declaring and initialising strings
char a[] = "Ravi"; /* size 5, worked out by the compiler */
char b[20] = "Ravi"; /* room for 19 characters plus '\0' */
char c[5] = {'R', 'a', 'v', 'i', '\0'}; /* same as a, written by hand */
char d[20]; /* empty array, fill it later */
| Declaration | sizeof | strlen | Notes |
|---|---|---|---|
char a[] = "Ravi"; |
5 | 4 | Exact fit |
char b[20] = "Ravi"; |
20 | 4 | Spare room for a longer string later |
char c[5] = {'R','a','v','i','\0'}; |
5 | 4 | You must add '\0' yourself |
char e[4] = "Ravi"; |
4 | Unsafe | No room for '\0', so this is not a proper string |
Common mistake: Assigning a string with
=after declaration, such asd = "Ravi";. That is a compile error because you cannot assign to an array. Usestrcpy(d, "Ravi");instead.
Printing a string character by character
Because a string is an array, you can loop over it. Stop when you reach '\0'.
#include <stdio.h>
int main(void) {
char word[] = "CODE";
int i;
for (i = 0; word[i] != '\0'; i++) {
printf("word[%d] = %c\n", i, word[i]);
}
printf("Length = %d\n", i);
return 0;
}
Output:
word[0] = C
word[1] = O
word[2] = D
word[3] = E
Length = 4
When the loop ends, i points at '\0', so it equals the length. This is how strlen works inside.
String input in C: scanf vs fgets
scanf("%s", ...) reads one word. It stops at the first space.
#include <stdio.h>
int main(void) {
char name[30];
printf("Enter your name: ");
scanf("%29s", name);
printf("Hello, %s\n", name);
return 0;
}
Sample run:
Enter your name: Ravi Kumar
Hello, Ravi
There is no & before name, because an array name already gives the address of its first element. The 29 in %29s stops scanf from writing more than 29 characters, leaving room for '\0'.
To read a full line with spaces, use fgets:
#include <stdio.h>
#include <string.h>
int main(void) {
char name[30];
printf("Enter your full name: ");
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0';
printf("Hello, %s!\n", name);
printf("Length: %zu\n", strlen(name));
return 0;
}
Sample run:
Enter your full name: Ravi Kumar
Hello, Ravi Kumar!
Length: 10
fgets reads up to sizeof(name) - 1 characters and keeps the Enter key as '\n' at the end. The strcspn line finds that '\n' and replaces it with '\0'. Without that line, the ! would print on the next line and the length would be 11.
Common mistake: Using
gets(name). It cannot know the size of the array, so long input overflows it. It was removed from the C standard in C11. Always usefgets.
String functions in C (string.h)
Add #include <string.h> to use these.
| Function | What it does | Example |
|---|---|---|
strlen(s) |
Length, not counting '\0' |
strlen("Hello") is 5 |
strcpy(dest, src) |
Copies src into dest |
strcpy(d, "Hi") |
strcat(dest, src) |
Adds src to the end of dest |
"Hello" + " World" |
strcmp(a, b) |
Compares. 0 if equal, negative if a comes first, positive if b comes first |
strcmp("cat", "cat") is 0 |
strncpy(dest, src, n) |
Copies at most n characters |
Safer copy, but may not add '\0' |
strchr(s, ch) |
Finds the first ch in s |
Returns a pointer, or NULL if not found |
strstr(s, sub) |
Finds sub inside s |
Returns a pointer, or NULL if not found |
strlen, strcpy and strcat
#include <stdio.h>
#include <string.h>
int main(void) {
char first[30] = "Hello";
char second[] = "World";
char copy[30];
strcpy(copy, first);
printf("copy : %s\n", copy);
strcat(first, " ");
strcat(first, second);
printf("joined : %s\n", first);
printf("length : %zu\n", strlen(first));
return 0;
}
Output:
copy : Hello
joined : Hello World
length : 11
strcpy and strcat do not check the size of the destination. first has room for 30 characters, which is enough for "Hello World". If the destination is too small, the program writes past the end of the array, which is a serious bug.
strcmp: comparing strings
strcmp returns 0 when the strings are equal. When they differ, the C standard only promises the sign (negative or positive), not the exact number, so always test against 0.
#include <stdio.h>
#include <string.h>
void compare(const char *a, const char *b) {
int r = strcmp(a, b);
if (r == 0) {
printf("%s and %s are equal\n", a, b);
} else if (r < 0) {
printf("%s comes before %s\n", a, b);
} else {
printf("%s comes after %s\n", a, b);
}
}
int main(void) {
compare("apple", "apple");
compare("apple", "banana");
compare("cat", "Cat");
return 0;
}
Output:
apple and apple are equal
apple comes before banana
cat comes after Cat
The comparison goes character by character using character codes. Lowercase 'c' is 99 and uppercase 'C' is 67, so "cat" comes after "Cat". This is why a simple password check should use strcmp(input, saved) == 0, never input == saved.
Two classic string programs
Count vowels in a string
#include <stdio.h>
#include <ctype.h>
int main(void) {
char text[] = "Programming";
int i, vowels = 0;
char ch;
for (i = 0; text[i] != '\0'; i++) {
ch = tolower(text[i]);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
}
}
printf("Vowels in %s: %d\n", text, vowels);
return 0;
}
Output:
Vowels in Programming: 3
tolower from <ctype.h> turns a letter into lowercase, so the check also catches capital vowels. The full version with consonants is in count the vowels and consonants in a string.
Reverse a string without strrev
#include <stdio.h>
#include <string.h>
int main(void) {
char s[] = "programming";
int left = 0;
int right = strlen(s) - 1;
char temp;
while (left < right) {
temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
printf("Reversed: %s\n", s);
return 0;
}
Output:
Reversed: gnimmargorp
Two positions start at the two ends and swap characters until they meet in the middle. strrev is not part of standard C, so this loop is the portable way. Compare the reversed string with the original using strcmp and you have a palindrome check.
Changing case with ctype.h
#include <stdio.h>
#include <ctype.h>
int main(void) {
char s[] = "hello world";
int i;
for (i = 0; s[i] != '\0'; i++) {
s[i] = toupper(s[i]);
}
printf("%s\n", s);
return 0;
}
Output:
HELLO WORLD
toupper changes lowercase letters and leaves everything else, such as the space, as it is. Other useful ctype.h functions are isalpha, isdigit, isspace and isupper.
Common mistakes with strings in C
| Mistake | Example | Fix |
|---|---|---|
No room for '\0' |
char s[4] = "Ravi"; |
Make the array at least one longer than the text |
Assigning with = |
s = "Hello"; |
strcpy(s, "Hello"); |
Comparing with == |
if (s1 == s2) |
if (strcmp(s1, s2) == 0) |
Using & with %s |
scanf("%s", &name); |
scanf("%29s", name); |
Expecting scanf("%s") to read spaces |
Input Ravi Kumar gives Ravi |
Use fgets |
Destination too small for strcat |
char a[6] = "Hello"; strcat(a, "!"); |
Size the destination for the final string plus '\0' |
| Changing a string literal | char *p = "Hi"; p[0] = 'h'; |
Use an array: char p[] = "Hi"; |
The last row needs pointers to understand. char *p = "Hi"; points to text the program must not change, while char p[] = "Hi"; makes your own copy. What is a pointer in C explains the difference between the two.
Quick revision
- A C string is a
chararray ending in'\0'. "Ravi"needs 5 bytes: 4 letters plus'\0'.strlencounts letters.sizeofcounts bytes in the array.scanf("%s")reads one word.fgetsreads a whole line.- Copy with
strcpy, join withstrcat, compare withstrcmp(...) == 0. - Always leave room for
'\0'in the destination.
Strings come up in almost every C lab exam and interview. Practise them with the C programming interview questions, and then group related data such as a name, roll number and marks with structures in C.
Frequently Asked Questions
What is a string in C?
What is the difference between strlen and sizeof for a string?
Why can't I compare strings with == in C?
Why should I not use gets in C?
Does C have a strrev function?
Want to Build Your Career in Java Full Stack with AI?
Join CodeBegun and train with working industry engineers — See the Java Full Stack course in Hyderabad

