String handling functions in c
Introduction to String Handling Functions in C
String handling is an essential aspect of programming in C language. Strings are a sequence of characters that represent textual data. C provides several built-in functions that can be used to manipulate and handle strings efficiently. In this blog, we will discuss the string handling functions in C language, their syntax, and provide examples to illustrate their usage.
String Handling Functions in C
1. strlen()
The strlen() function returns the length of a given string.
The syntax of the function is as follows:
size_t strlen(const char *str);
Here, str is the string whose length needs to be determined. The function returns the length of the string.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[50] = "Hello,world!";
printf("Length of the string is : %d\n ", strlen(str));
return 0;
}
Output:
Length of the string is: 13
2. strcpy()
The strcpy() function is used to copy one string to another.
The syntax of the function is as follows:
char *strcpy( char *dest,const char *src);
Here, dest is the destination string and src is the source string. The function returns the destination string after the copy operation.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char src[50] = "Hello,world!";
char dest[50];
strcpy(dest, src); printf("Destination string is : %s\n ", dest);
return 0;
}
Output:
Destination string is: Hello, world!
3. strcat()
The strcat() function is used to concatenate two strings.
The syntax of the function is as follows:
char *strcat( char *dest,const char *src);
Here, dest is the destination string and src is the source string. The function returns the concatenated string.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello, ";
char str2[50] = "world!";
strcat(str1, str2); printf("Concatenated string is : %s\n ", str1);
return 0;
}
Output:
Concatenated string is: Hello, world!
4. strcmp()
The strcmp() function is used to compare two strings.
The syntax of the function is as follows:
int *strcmp(const char *str1,const char *str2);
Here, str1 and str2 are the two strings to be compared. The function returns 0 if the two strings are equal, a negative integer if str1 is less than str2, and a positive integer if str1 is greater than str2.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[50] = "Hello, world!";
char str2[50] = "Hello, world!";
int result = strcmp(str1, str2); if (result == 0) {
printf("strings are equal.\n");
}
else {
printf("strings are not equal.\n");
}
return 0;
}
Output:
strings are equal.
Conclusion
String handling is an essential aspect of programming in C language. C provides several built-in functions that can be used to manipulate and handle strings efficiently. In this blog, we have discussed some of the most
Share Your Feedback Here !!