string_h_function_guide
string_h_function_guide
h Functions in C
This document contains a comprehensive guide to the functions in the C standard library's string.h
header, including each function's description, return type, example code, and use cases.
1. strlen()
Description: Returns the length of a string (excluding the null terminator).
Return Type: size_t
Example Code:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
printf("Length: %zu\n", strlen(str));
return 0;
}
Output:
Length: 13
Use Case: This function is typically used when you need to determine the length of a string to
allocate memory or when working with string operations that require a length value.
strcpy()
Description: Copies one string into another.
Return Type: char *strcpy(char *dest, const char *src);
Example Code:
#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello";
char dest[10];
strcpy(dest, src);
printf("%s\n", dest);
return 0;
}
Output:
Hello
Use Case: Used to copy strings, often used when transferring data between variables.
strcat()
Description: Appends one string to the end of another.
Return Type: char *strcat(char *dest, const char *src);
Example Code:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = " World";
strcat(str1, str2);
printf("%s\n", str1);
return 0;
}
Output:
Hello World
Use Case: Used to concatenate strings, typically used in text processing or building strings
dynamically.
strcmp()
Description: Compares two strings lexicographically.
Return Type: int strcmp(const char *str1, const char *str2);
Example Code:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Apple";
char str2[] = "Banana";
int result = strcmp(str1, str2);
printf("%d\n", result);
return 0;
}
Output:
-1
Use Case: Used to compare strings, useful for sorting, searching, or validating string data.