C Strings

🔤 C Strings (Complete Tutorial: Beginner → Advanced)
In C language, a string is a sequence of characters stored in a character array and terminated by a null character '\0'.
Understanding strings is essential for input/output, file handling, DSA, and interviews.
1️⃣ What Is a String in C?
Memory layout:
✔ '\0' marks the end of the string
2️⃣ Declaring Strings
1) Character Array
2) Initialize at Declaration
3) Character-by-Character
3️⃣ String Input & Output ⭐
Output
Input (Recommended)
⚠️ Avoid:
4️⃣ scanf() vs fgets()
| Feature | scanf("%s") | fgets() |
|---|---|---|
| Reads spaces | ❌ No | ✅ Yes |
| Buffer safety | ❌ No | ✅ Yes |
| Recommended | ⚠️ Limited | ✅ Yes |
5️⃣ Common String Functions (<string.h>) ⭐
Include:
Length
Copy
Concatenate
Compare
Search
Tokenize
6️⃣ sizeof() vs strlen() ⭐
7️⃣ Strings & Pointers (Very Important)
⚠️ Don’t modify string literals:
8️⃣ Passing Strings to Functions
9️⃣ Common String Operations (Manual) ⭐
Reverse a String
Count Characters
🔟 Common Mistakes ❌
❌ Forgetting '\0'
❌ Buffer overflow with strcpy()
❌ Comparing strings using ==
❌ Using gets()
❌ Modifying string literals
✔ Correct comparison:
📌 Interview Questions (Must Prepare)
What is a string in C?
Why is
'\0'required?Difference between
sizeof()andstrlen()?char *svschar s[]?Why
==can’t compare strings?Is
strcpy()safe?
🔥 Real-Life Use Cases
User input & validation
File parsing (CSV, logs)
Networking protocols
Embedded firmware
Competitive programming
✅ Summary
✔ Strings are null-terminated char arrays
✔ Use <string.h> functions carefully
✔ Prefer fgets() for input
✔ Avoid unsafe functions
✔ Critical for projects, DSA & interviews
