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
- A string is a sequence of characters stored in an array.
- Ends with a null character
\0to mark the end of the string. - Strings are treated as character arrays in C.
2. Syntax
char string_name[size];
char– character typestring_name– name of the stringsize– 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
- Strings are arrays of characters ending with
\0 scanf("%s", str)reads single word;fgets()reads full line- Always allocate enough space for null character
- Strings can be manipulated using standard string functions