C Strings

C Tutorial

🔤 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?

char name[] = "C Language";

Memory layout:

C L a n g u a g e \0

'\0' marks the end of the string


2️⃣ Declaring Strings

1) Character Array

char s[20];

2) Initialize at Declaration

char s[] = "Hello";

3) Character-by-Character

char s[] = {'H','e','l','l','o','\0'};

3️⃣ String Input & Output ⭐

Output


 

Input (Recommended)

fgets(s, sizeof(s), stdin);

⚠️ Avoid:

gets(s); // unsafe ❌

4️⃣ scanf() vs fgets()

Featurescanf("%s")fgets()
Reads spaces❌ No✅ Yes
Buffer safety❌ No✅ Yes
Recommended⚠️ Limited✅ Yes

5️⃣ Common String Functions (<string.h>) ⭐

Include:

#include <string.h>

Length

strlen(s); // excludes '\0'

Copy

strcpy(dest, src); // be careful with size
strncpy(dest, src, n); // safer (ensure '\0')

Concatenate

strcat(s1, s2);
strncat(s1, s2, n);

Compare

strcmp(s1, s2); // 0 if equal
strncmp(s1, s2, n);

Search

strchr(s, 'a'); // first occurrence
strrchr(s, 'a'); // last occurrence
strstr(s, "sub"); // substring

Tokenize

strtok(s, ","); // modifies original string

6️⃣ sizeof() vs strlen()


 


7️⃣ Strings & Pointers (Very Important)


 

⚠️ Don’t modify string literals:

p[0] = 'h'; // undefined behavior ❌

8️⃣ Passing Strings to Functions


✔ Arrays decay to pointers when passed to functions


9️⃣ Common String Operations (Manual) ⭐

Reverse a String


 

Count Characters

int count = 0;
while (s[count] != '\0') count++;

🔟 Common Mistakes ❌

❌ Forgetting '\0'
❌ Buffer overflow with strcpy()
❌ Comparing strings using ==
❌ Using gets()
❌ Modifying string literals

✔ Correct comparison:

strcmp(s1, s2) == 0

📌 Interview Questions (Must Prepare)

  1. What is a string in C?

  2. Why is '\0' required?

  3. Difference between sizeof() and strlen()?

  4. char *s vs char s[]?

  5. Why == can’t compare strings?

  6. 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

You may also like...