Strings in C Programming (Complete Guide with Examples)


This tutorial explains strings in C, which are arrays of characters ending with a null character \0. It covers declaration, initialization, input/output, and basic operations, helping beginners work with text data effectively.

1. What is a String in C

  1. A string is a sequence of characters stored in an array.
  2. Ends with a null character \0 to mark the end of the string.
  3. Strings are treated as character arrays in C.

2. Syntax


char string_name[size];
  1. char – character type
  2. string_name – name of the string
  3. size – number of characters (include space for \0)

Example: Declaration and Initialization


char name[20]; // Declaration
char city[10] = "Mumbai"; // Initialization
char country[] = "India"; // Size determined automatically

3. Input and Output of Strings

Using scanf()


char name[20];
printf("Enter your name: ");
scanf("%s", name); // Reads input until first space
printf("Hello, %s\n", name);

Using gets() and puts()


char name[50];
printf("Enter full name: ");
gets(name); // Reads string with spaces
puts(name); // Prints the string

Note: gets() is unsafe; use fgets() in modern C.

Using fgets() (Safe)


char name[50];
printf("Enter full name: ");
fgets(name, sizeof(name), stdin); // Includes newline character
printf("Hello, %s", name);

4. Example Program: String Input and Display


#include <stdio.h>

int main() {
char name[50];

printf("Enter your name: ");
scanf("%s", name); // Input without spaces

printf("Hello, %s!\n", name);
return 0;
}

Sample Output:


Enter your name: Muni
Hello, Muni!

5. Example Program: String with Spaces


#include <stdio.h>

int main() {
char name[50];

printf("Enter full name: ");
fgets(name, sizeof(name), stdin);

printf("Welcome, %s", name);
return 0;
}

Sample Output:


Enter full name: Muni Patil
Welcome, Muni Patil

6. Key Points to Remember

  1. Strings are arrays of characters ending with \0
  2. scanf("%s", str) reads single word; fgets() reads full line
  3. Always allocate enough space for null character
  4. Strings can be manipulated using standard string functions