Common String Functions
C programming provides a set of standard library functions for manipulating strings. These functions are declared in the <string.h>
header file and offer various operations to work with character arrays. Let's explore some common string functions and their usage.
1. strlen
- String Length
strlen
- String Length#include <string.h>
size_t strlen(const char *str);
This function returns the length of the input string, excluding the null character. It calculates the number of characters in the string.
const char *message = "Hello, World!";
size_t length = strlen(message); // Returns 13
2. strcpy
- String Copy
strcpy
- String Copy#include <string.h>
char *strcpy(char *dest, const char *src);
This function copies the contents of the source string (src
) to the destination string (dest
). It includes the null character in the copied sequence.
char source[] = "Copy me!";
char destination[20];
strcpy(destination, source); // destination now contains "Copy me!"
3. strcat
- String Concatenate
strcat
- String Concatenate#include <string.h>
char *strcat(char *dest, const char *src);
This function appends the contents of the source string (src
) to the destination string (dest
). The destination string must have enough space to accommodate both strings.
char greeting[20] = "Hello";
strcat(greeting, ", World!"); // greeting now contains "Hello, World!"
4. strcmp
- String Compare
strcmp
- String Compare#include <string.h>
int strcmp(const char *str1, const char *str2);
This function compares two strings (str1
and str2
) lexicographically. It returns an integer less than, equal to, or greater than zero, indicating whether the first string is less than, equal to, or greater than the second string.
const char *string1 = "apple";
const char *string2 = "banana";
int result = strcmp(string1, string2); // Returns a value < 0
5. strncpy
- String Copy with Length Limit
strncpy
- String Copy with Length Limit#include <string.h>
char *strncpy(char *dest, const char *src, size_t n);
This function copies at most n
characters from the source string (src
) to the destination string (dest
). It ensures that the destination is null-terminated if n
is sufficient.
char source[] = "Copy me!";
char destination[5];
strncpy(destination, source, 4); // destination now contains "Copy"
These are just a few examples of the many string functions available in C. Understanding and using these functions appropriately will enhance your ability to work with strings in C programming.
If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!
Was this helpful?