The short answer
C has no separate string library that you need to install, and it has no string type. Its string handling comes from the standard header <string.h>, along with a few other standard headers. A string in C is an array of char that ends with a null character, and the functions in <string.h> work on those arrays.
What C uses instead of a string type
A C string is a run of characters followed by a null character, written '\0'. The null character marks the end of the text. C does not store the length alongside the text, so functions find the end by reading until they reach the null character.
char greeting[] = "Hello";
This array holds five letters plus the null character, so it takes six bytes.
Functions in string.h
<string.h> declares the common functions for working with C strings. The main ones include:
strlenreturns the number of characters before the null character.strcpycopies one string into another.strcatadds one string to the end of another. It is covered in how to concatenate strings in c.strcmpcompares two strings and returns 0 when they are equal. The details are in how to compare two strings in c.strchrandstrstrsearch for a character or a substring.
Functions with an n in the name, such as strncpy, take a length limit. They still need care with the null character.
Other standard headers
A few other standard headers also help with text:
<stdio.h>for printing and reading text.<stdlib.h>for converting text to numbers, such asatoi.<ctype.h>for checking characters, such asisdigitandisalpha.
Example
#include <stdio.h>
#include <string.h>
int main(void) {
char name[] = "Ada";
printf("Length: %zu\n", strlen(name));
printf("Same as Ada: %d\n", strcmp(name, "Ada") == 0);
return 0;
}
Output:
Length: 3
Same as Ada: 1
The %d format prints 1 here because the comparison is true.
What about C++?
C++ has a string type. std::string is declared in <string> and has member functions for searching, appending and comparing text, so C++ code usually does not need the C functions. Those functions are still available through <cstring>. The member functions of std::string are described in c string methods.
Third-party libraries
Some third-party libraries add their own string types to C. They are not part of the C standard library, so you need to install and link them yourself.
Summary
- C has no string type and no separate string library to install.
- Strings are
chararrays that end in a null character. <string.h>provides the common functions for working with them.- C++ offers
std::stringin<string>.