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– character typestring_name– name of the stringsize– number of characters (include space for\0)
Example: Declaration and Initialization
3. Input and Output of Strings
Using scanf()
Using gets() and puts()
Note: gets() is unsafe; use fgets() in modern C.
Using fgets() (Safe)
4. Example Program: String Input and Display
Sample Output:
5. Example Program: String with Spaces
Sample Output:
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