Nearby lessons

42 of 72

C - String Introduction

Learn what a string is in C, how to declare and initialize strings, and how to read and display strings using simple examples.

What Is a String?

A string is a collection of characters. In C, we store strings using character arrays.

For example, "Hello" is a string containing five letters.

C adds a special character called the null character (\0) at the end of a string initialized using a string literal.

Example01
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char name[] = "Hello";
6 
7 printf("%s", name);
8 
9 return 0;
10}
Output
Hello

Declaring and Initializing a String

We can declare a character array and assign a string to it.

Example: char name[20] = "Rahul";

The array has space for 20 characters, including the ending null character.

Example02
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char name[20] = "Rahul";
6 
7 printf("Name: %s", name);
8 
9 return 0;
10}
Output
Name: Rahul

Understanding the Null Character

The null character (\0) tells C where a string ends.

The string "Hello" contains five letters and one null character. Therefore, it needs six character positions when stored as a string.

Example03
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char name[] = "Hello";
6 
7 printf("String: %s\n", name);
8 printf("Array size: %zu", sizeof(name));
9 
10 return 0;
11}
Output
String: Hello
Array size: 6

Displaying Characters Using a Loop

We can use a loop to display each character of a string one by one. The loop stops when it reaches \0.

Example04
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char name[] = "Hello";
6 int i;
7 
8 for (i = 0; name[i] != '\0'; i++)
9 {
10 printf("%c\n", name[i]);
11 }
12 
13 return 0;
14}
Output
H
e
l
l
o

Common Mistakes

  • Forgetting to leave space for the ending null character.
  • Expecting scanf("%s", name) to read a full name with spaces.
  • Using gets(), which is unsafe. Use fgets() instead.
  • Accessing characters outside the valid array indexes.
📝 Key Takeaways
  • C stores strings using character arrays.
  • The null character (\0) marks the end of a string.
  • A string needs space for its characters and the null character.
  • scanf("%s", name) reads only one word.
  • fgets() can read a line containing spaces.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3