Nearby lessons

69 of 124

C - String Functions (string.h)

String Functions (string.h) is one of the foundational topics in C programming. This lesson explains The String Functions (string.h) with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

The String Functions (string.h)

Include #include <string.h> and use these ready-made functions:

FunctionWhat it doesExample
strlen(s)Length (number of characters before \0)strlen("Rahul") → 5
strcpy(dest, src)Copy src into deststrcpy(b, a)
strcat(dest, src)Join src at the end of deststrcat(b, a)
strcmp(a, b)Compare two strings (0 = equal)strcmp(a, b)
strlwr(s)Convert to lowercasestrlwr(s)
strupr(s)Convert to uppercasestrupr(s)
strrev(s)Reverse the stringstrrev(s)
In simple words: <string.h> is a ready-made toolkit for text — strlen measures, strcpy copies, strcat joins, strcmp compares. You write the plan; the toolkit does the heavy work.
Trainer's Note: You cannot compare or copy strings with = and ==. b = a and if (a == b) are WRONG for strings — they compare addresses, not the text. Always use strcpy and strcmp.
Example01
CCode Cell
1#include <stdio.h>
2#include <string.h>
3 
4void main()
5{
6 char a[20] = "Hello";
7 char b[20];
8 
9 strcpy(b, a); // b becomes "Hello"
10 strcat(b, " World"); // b becomes "Hello World"
11 
12 printf("%s\n", b);
13 printf("Length: %d\n", strlen(b));
14 printf("Compare: %d\n", strcmp(a, "Hello")); // 0 = equal
15}
Output

Hello World
Length: 11
Compare: 0
      
📝 Key Takeaways
  • A string = char array + a null character '\0' at the end.
  • Remember to leave room for '\0' when sizing arrays.
  • scanf %s reads one word; fgets reads a full line safely.
  • Use string.h functions: strlen, strcpy, strcat, strcmp.
  • Never use = or == for strings — use strcpy and strcmp.
  • Loops can count, reverse and check strings from scratch.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3