In C programming, a string is text stored as a sequence of characters. C has no built-in string type, so a C string is a char array that ends with the null character, '\0'. C++ adds std::string, a class from the <string> header that tracks its own length and manages its own memory. The examples below show both.
Single characters and string literals
A single character in single quotes is a char. Text in double quotes is a string, and it always includes a null character at the end.
char letter = 'A'; /* one character */
char word[] = "A"; /* two elements: 'A' and '\0' */
Strings in C: char arrays
#include <stdio.h>
#include <string.h>
int main(void) {
char city[] = "Lisbon";
printf("%s\n", city); /* Lisbon */
printf("%zu\n", strlen(city)); /* 6 */
return 0;
}
The %s conversion prints a string until it reaches the null character. The format is explained further in What is %s and %d in C.
Strings in C++: std::string
#include <iostream>
#include <string>
int main() {
std::string city = "Lisbon";
city += ", Portugal";
std::cout << city << '\n'; // Lisbon, Portugal
std::cout << city.size() << '\n'; // 16
return 0;
}
The std::string object grows as the text grows, so += works without a buffer size. Joining strings in more detail is covered in how to concatenate strings in c.
Choosing between them
For new C++ code, std::string is usually the better choice, because it manages its size and memory for you. C-style strings still matter when you work with C libraries, with older code, or with functions that take a const char*. The member functions of std::string are listed in C++ String Methods.
Comparison also differs. std::string supports ==, while a C string needs a function such as strcmp(). The C version is shown in how to compare two strings in c.
Common beginner mistakes
- Using single quotes for text.
'A'is one character, while"A"is a string with two elements. - Forgetting the slot for the null character in a char array.
- Comparing C strings with
==. - Passing a
std::stringto a function that expects achar *without callingc_str()first.
Start with the type that fits your code. Most C++ code uses std::string, and char arrays show up when you work close to C.