<cstring> ReferenceThe <cstring> library in C++ provides a set of functions for manipulating C-style strings. These functions are essential for tasks such as string length calculation, copying, concatenation, comparison, and tokenization. Understanding these functions is crucial for any C++ programmer dealing with text data.
C-style strings are arrays of characters terminated by the null character ('\0'). The <cstring> library offers a variety of functions to perform operations on these strings efficiently. In this tutorial, we will explore some of the most commonly used functions: strlen, strcpy, strcat, strcmp, strncpy, memcpy, memset, and strtok.
strlenThe strlen function calculates the length of a C-style string (excluding the null terminator).
1size_t strlen(const char *str);
1#include <iostream>2#include <cstring>34int main() {5const char str[] = "Hello, World!";6std::cout << "Length of "" << str << "" is " << strlen(str) << std::endl;7return 0;8}
strcatThe strcat function appends a string to the end of another string.
1char *strcat(char *dest, const char *src);
dest: Pointer to the destination array where the content is to be appended.src: C-style string to append.1#include <iostream>2#include <cstring>34int main() {5char dest[50] = "Hello, ";6const char src[] = "World!";7strcat(dest, src);8std::cout << "Concatenated string: " << dest << std::endl;9return 0;10}
strncpyThe strncpy function copies up to a specified number of characters from one string to another.
1char *strncpy(char *dest, const char *src, size_t n);
dest: Pointer to the destination array where the content is to be copied.src: C-style string to copy.n: Maximum number of characters to copy.1#include <iostream>2#include <cstring>34int main() {5char dest[50];6const char src[] = "Hello, World!";7strncpy(dest, src, 5);8dest[5] = '