String Functions in C (strlen, strcpy, strcmp Explained Simply)
After learning strings in C, the next step is understanding string functions.
These functions make your work easier when dealing with text.
Let’s look at the most important ones in a simple way.
1. strlen() – Find Length of String
The strlen() function is used to find the length of a string.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char name[] = "Ali";
printf("%d", strlen(name));
return 0;
}👉 Output: 3
2. strcpy() – Copy One String to Another
The strcpy() function copies one string into another.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[10];
strcpy(str2, str1);
printf("%s", str2);
return 0;
}👉 Output: Hello
3. strcmp() – Compare Two Strings
The strcmp() function compares two strings.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Ali";
char str2[] = "Ali";
if(strcmp(str1, str2) == 0) {
printf("Strings are equal");
} else {
printf("Strings are not equal");
}
return 0;
}👉 Output: Strings are equal
Why These Functions Matter
These functions help you:
- Work with text easily
- Save time
- Write cleaner code
Final Thoughts
String functions are very useful in C programming.
Once you understand them, handling text becomes much easier.
Thanks for reading!
Comments
Post a Comment