C Language | Advanced Features | String Operations - strcat(), strlen(), strcpy(), strcmp(), and More
The standard library provides functions for joining, measuring, copying, comparing, and formatting strings.
Joining and Copying Strings
String functions are declared in string.h.
char *strcat(char *destination, const char *source);
strcat() appends source to a null-terminated string in destination. The destination buffer must have enough space, and the two regions must not overlap.
Code 1
#include <stdio.h>
#include <string.h>
int main() {
char text[256] = "Kitty on your lap";
strcat(text , " and a book");
printf("%s\n" , text);
return 0;
}
Use strlen() to obtain a string length, excluding the terminating null character.
size_t strlen(const char *string);
Use strcpy() to copy a null-terminated string.
char *strcpy(char *destination, const char *source);
Code 2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
const char *left = "Kitty on your lap";
const char *right = " and a book";
char *text = malloc(strlen(left) + strlen(right) + 1);
if (text == NULL) return 1;
strcpy(text , left);
strcat(text , right);
printf("%s\n" , text);
free(text);
return 0;
}
Comparing Strings
Use strcmp() to compare string contents.
int strcmp(const char *left, const char *right);
The function returns zero for equal strings, a negative value when left sorts before right, and a positive value when left sorts after right.
Code 3
#include <stdio.h>
#include <string.h>
int main() {
char left[255] , right[255];
printf("Enter two strings. >");
scanf("%254s %254s" , left , right);
if (strcmp(left , right) == 0)
printf("The strings are equal.\n");
else if (strcmp(left , right) < 0)
printf("%s sorts before %s.\n" , left , right);
else
printf("%s sorts after %s.\n" , left , right);
return 0;
}
Formatting Strings
sprintf() writes formatted output to a buffer, while sscanf() reads formatted values from a string.
int sprintf(char *buffer, const char *format, ...);
int sscanf(const char *buffer, const char *format, ...);
Code 4
#include <stdio.h>
int main() {
char text[256];
sprintf(text , "Today is %d-%02d-%02d." , 2017 , 11 , 26);
printf("%s\n" , text);
return 0;
}
In production code, prefer bounded alternatives such as snprintf() when available so that output cannot exceed the destination buffer.