String Handling in C Programming – Complete Guide to strlen, strcpy, strcmp and More

String Handling in C Programming – Complete Guide to strlen, strcpy, strcmp and More

Strings are one of the most important topics in C programming. Almost every real-world program uses strings in some form.

In this article, you will learn string handling in C programming step by step, including the most commonly used string functions with simple explanations.

What Is a String in C?

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

Example:

char name[] = "Coding";

Why String Handling Is Important?

  • Used in user input and output
  • Required for file handling
  • Important for interview questions

String Header File

All string functions are defined in the string.h header file.

#include <string.h>

strlen() Function

The strlen() function returns the length of a string excluding the null character.

char str[] = "Hello";
printf("%d", strlen(str));

strcpy() Function

The strcpy() function copies one string into another.

char src[] = "C Programming";
char dest[20];
strcpy(dest, src);

strcmp() Function

The strcmp() function compares two strings.

It returns:

  • 0 if strings are equal
  • Positive value if first string is greater
  • Negative value if first string is smaller

strcat() Function

The strcat() function joins two strings.

char s1[20] = "Hello ";
char s2[] = "World";
strcat(s1, s2);

strncpy() and strncat()

These functions copy or concatenate a limited number of characters.

They help avoid buffer overflow issues.

Common Mistakes in String Handling

  • Forgetting null terminator
  • Using insufficient array size
  • Not including string.h

String Input Using gets() and fgets()

gets() is unsafe and should be avoided.

fgets() is safer and recommended.

Interview Questions on Strings

  • Difference between string and character array
  • What does strcmp return?
  • Why is gets unsafe?

Final Conclusion

String handling is a core concept in C programming. Mastering string functions will help you write real-world programs and crack interviews easily.

Next Post: File Handling in C Programming (Read, Write, Append)

Comments

Popular posts from this blog

Graph Data Structure – Complete Beginner to Advanced Guide with BFS, DFS and Examples

Top Coding Mistakes Beginners Make (And How to Fix Them the Right Way)

Top 10 Free Coding Websites Every Beginner Should Use in 2026