C String Functions

C Tutorial

🔤 C String Functions (Complete Tutorial: Beginner → Advanced)

In C language, strings are handled using character arrays and the string library
👉 Header file: <string.h>

C does not have a built-in string data type, so string functions are very important for real programs and interviews.


1️⃣ What Is a String in C?

A string is an array of characters terminated by a null character '\0'.

char name[] = "C Language";

Memory:

C L a n g u a g e \0

2️⃣ Include String Library

#include <string.h>

3️⃣ Most Common String Functions ⭐


🔹 strlen() – String Length

✔ Does NOT count '\0'


🔹 strcpy() – Copy String


 

⚠️ Destination must have enough space


🔹 strncpy() – Safer Copy

✔ Limits copy size


🔹 strcat() – Concatenate Strings


 

✔ Result → "Hello World"


🔹 strncat() – Safe Concatenation

strncat(s1, s2, 3);

🔹 strcmp() – Compare Strings ⭐

strcmp("abc", "abc"); // 0
strcmp("abc", "abd"); // < 0
strcmp("abd", "abc"); // > 0

✔ Case-sensitive


🔹 strncmp() – Compare Limited Characters

strncmp("abcdef", "abcxyz", 3); // 0

4️⃣ String Search Functions 🔍


🔹 strchr() – Find Character

char s[] = "Hello";
char *p = strchr(s, 'e');

✔ Returns pointer to first occurrence


🔹 strrchr() – Find Last Occurrence

strrchr("banana", 'a');

🔹 strstr() – Find Substring ⭐

char s[] = "C Programming";
printf("%s", strstr(s, "Pro"));

✔ Output → Programming


5️⃣ String Tokenization 🔥

🔹 strtok() – Split String


 

✔ Used in CSV parsing
⚠️ Modifies original string


6️⃣ Case Conversion (Non-Standard but Common)


 

(For strings, loop manually)


7️⃣ String Input & Output Recap

Input

fgets(name, sizeof(name), stdin);

Output

puts(name);

8️⃣ Common String Mistakes ❌

❌ Forgetting '\0'
❌ Using gets() (unsafe)
❌ Buffer overflow in strcpy()
❌ Comparing strings using ==

✔ Correct comparison:

strcmp(s1, s2) == 0

9️⃣ sizeof() vs strlen()

char s[] = "Hello";

sizeof(s); // 6 (includes ‘\0’)
strlen(s); // 5


🔟 Important Interview Questions

  1. Difference between strlen() and sizeof()

  2. Why strcmp() is used instead of ==

  3. Is strcpy() safe?

  4. How strtok() works internally

  5. What is null-terminated string?


🔥 Real-Life Use Cases

  • Input validation

  • File parsing

  • URL & protocol handling

  • Embedded firmware

  • Competitive programming


✅ Summary

✔ Strings are character arrays
<string.h> provides powerful utilities
✔ Always handle buffer size carefully
strcmp() for comparison, not ==
✔ Extremely important for interviews & projects

You may also like...