14 Jan String Functions in C
C provides several standard library functions to work with strings. To work with string functions in C language, use the following header file:
1 2 3 |
string.h |
Include it in your program file:
1 2 3 |
#include <string.h> |
Let us now see some popular string functions in C language and what they will return after execution:
- strlen(): returns the length of a given string
- strcmp(): compares two strings
- strcpy(): copies one string to another
- strcat(): concatenates two strings
Let us see an example implementing all the above string functions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <stdio.h> #include <string.h> int main() { char str1[20] = "Hello"; char str2[20]; // Copying string strcpy(str2, str1); printf("str2 after strcpy: %s\n", str2); // Concatenating strings strcat(str1, ", Amit!"); printf("str1 after strcat: %s\n", str1); // String length int len = strlen(str1); printf("Length of str1: %d\n", len); // Comparing strings int result = strcmp(str1, str2); if (result == 0) { printf("str1 and str2 are equal\n"); } else { printf("str1 and str2 are not equal\n"); } return 0; } |
Output
1 2 3 4 5 6 |
str2 after strcpy: Hello str1 after strcat: Hello, Amit! Length of str1: 12 str1 and str2 are not equal |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments