string.h is a built-in header file in C that provides several functions for string manipulation. To access these functions in C++, we can #include <cstring>
, but they still output a character pointer, not a string.
Data types
size_t
: the unsigned integer type. Guaranteed to be large enough to represent the size of the largest possible object on the platform you’re using.
Functions
size_t strlen(const char *str)
: takes in a string and counts characters up to but not including the null character.char* strcpy(char *dest, char *src)
: copies one string to another string.char* strncpy(char *dest, char *src, size_t n)
: memory-safe implementation ofstrcpy
, copies specified number of characters.char* strcat(char *dest, const char *src)
: appends source string to the back of the destination string, including the null character.char* strncat(char *dest, char *src, size_t n)
: memory-safe implementation ofstrcat
.int strcmp(const char *fir, const char *sec)
: compares strings against each other. If both are identical, it spits out a zero. If the first comes before the second in the dictionary, it spits out a negative number. Otherwise it spits out a positive number.int strncmp(const char *p, const char *q, int n)
: memory-safe implementation ofstrcmp
.char* strchr(char *s, char c)
: returns a pointer to the first occurrence ofc
— we can get the index by subtracting the pointer tos
.char* strstr(char *s1, char *s2)
: returns pointer to beginning of sub-string occurrence.void* memcpy(void *dest, const void *src, size_t n)
: copies some memory from source to destination. Note a useful application is to setn
as somesizeof(<type>)
.