14 Jan String Functions in C
C provides several standard library functions to work with strings. Before moving further, we’ve prepared a video tutorial to understand what String Functions are in C:
Video: String Functions in C
Video: String Functions in C (Hindi)
To work with string functions in the C language, use the following header file:
string.h
Include it in your program file:
#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:
#include <stdio.h>
#include <string.h>
int main() {
// This initializes a character array str1 with the string "Hello"
char str1[20] = "Hello";
/* This declares an empty character array str2 with space for 20
characters, but it doesn't initialize it with any value. */
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
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