strlen()
The strlen() function is used to find the length of a string. It returns the number of characters in
a string, excluding the null terminator ('\0').
Example
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "Gfg";
// Finding and printing length of string s
printf("%lu", strlen(s));
return 0;
Output
strcpy()
The strcpy() function copies a string from the source to the destination. It copies the entire
string, including the null terminator.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello";
char dest[20];
// Copies "Hello" to dest
strcpy(dest, src);
printf("%s", dest);
return 0;
Output
Hello
strncpy()
The strncpy() function is similar to strcpy(), but it copies at most n bytes from source to
destination string. If source is shorter than n, strncpy() adds a null character to destination to
ensure n characters are written.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello";
char dest[20];
// Copies "Hello" to dest
strncpy(dest, src, 4);
printf("%s", dest);
return 0;
Output
Hell
strcat()
The strcat() function is used to concatenate (append) one string to the end of another. It
appends the source string to the destination string, replacing the null terminator of the
destination with the source string’s content.
Example
#include <stdio.h>
#include <string.h>
int main() {
char s1[30] = "Hello, ";
char s2[] = "Geeks!";
// Appends "Geeks!" to "Hello, "
strcat(s1, s2);
printf("%s", s1);
return 0;
Output
Hello, Geeks!
strncat()
In C, there is a function strncat() similar to strcat(). This function appends not more than n
characters from the string pointed to by source to the end of the string pointed to
by destination plus a terminating NULL character.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char s1[30] = "Hello, ";
char s2[] = "Geeks!";
// Appends "Geeks!" to "Hello, "
strncat(s1, s2, 4);
printf("%s", s1);
return 0;
Output
Hello, Geek
strcmp()
The strcmp() is a built-in library function in C. This function takes two strings as arguments,
compares these two strings lexicographically and returns an integer value as a result of
comparison.
Example
#include <stdio.h>
#include <string.h>
int main() {
char s1[] = "Apple";
char s2[] = "Applet";
// Compare two strings
// and print result
int res = strcmp(s1, s2);
if (res == 0)
printf("s1 and s2 are same");
else if (res < 0)
printf("s1 is lexicographically "
"smaller than s2");
else
printf("s1 is lexicographically "
"greater than s2");
return 0;
Output
s1 is lexicographically smaller than s2
sprintf()
The sprintf() function is used to format a string and store it in a buffer. It is similar to printf(), but
instead of printing the result, it stores it in a string.
Example:
#include <stdio.h>
int main() {
char s[50];
int n = 10;
// Output formatted string into string bugger s
sprintf(s, "The value is %d", n);
printf("%s", s);
return 0;
Output
The value is 10