String Handling Functions in C (strlen, strcpy, strcmp, strcat with Examples)
This tutorial explains the commonly used string handling functions in C, including strlen, strcpy, strcmp, and strcat. It provides syntax, examples, and practical usage to help beginners manipulate strings efficiently in C programming.
1. strlen() – String Length
Purpose: Returns the length of a string (excluding the null character \0).
Syntax:
#include <string.h>
size_t strlen(const char *str);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char name[] = "Muni";
printf("Length of '%s' is %lu\n", name, strlen(name));
return 0;
}
Output:
Length of 'Muni' is 4
2. strcpy() – Copy String
Purpose: Copies the source string into the destination string.
Syntax:
#include <string.h>
char *strcpy(char *destination, const char *source);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello";
char dest[20];
strcpy(dest, src);
printf("Destination string: %s\n", dest);
return 0;
}
Output:
Destination string: Hello
3. strcmp() – Compare Strings
Purpose: Compares two strings.
- Returns
0if strings are equal - Returns positive if first string > second
- Returns negative if first string < second
Syntax:
#include <string.h>
int strcmp(const char *str1, const char *str2);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
if(result == 0)
printf("Strings are equal\n");
else if(result < 0)
printf("%s is less than %s\n", str1, str2);
else
printf("%s is greater than %s\n", str1, str2);
return 0;
}
Output:
apple is less than banana
4. strcat() – Concatenate Strings
Purpose: Appends the source string to the end of the destination string.
Syntax:
#include <string.h>
char *strcat(char *destination, const char *source);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
Output:
Concatenated string: Hello, World!
5. Key Points to Remember
- Include
#include <string.h>to use string functions strlen()does not count null characterstrcpy()overwrites the destination stringstrcmp()compares ASCII values of charactersstrcat()requires enough space in the destination string