In this tutorial, we're going to dive into the world of C-style strings and std::string in the C++ language. String handling is a fundamental skill in any language, and in C++, there are two primary ways to work with them.
The goal of this tutorial is to give you a clear understanding of:
Prerequisites: Basic understanding of C++ syntax
C-style strings are essentially arrays of characters that are terminated by a null character ('\0'). This null character indicates the end of the string. To declare a C-style string, you can do it like this:
char cstr[] = "Hello, world!";
In the above example, cstr
is an array of characters. It's important to note that the size of the array is one more than the number of characters in the string because of the null character.
The std::string is a class in the C++ Standard Library designed to manipulate strings in a more intuitive way. To declare a std::string, you can do it like this:
std::string str = "Hello, world!";
In the above example, str
is an instance of the std::string class. Unlike C-style strings, std::strings automatically manage their size.
#include <iostream>
int main() {
char cstr[] = "Hello, world!";
std::cout << cstr;
return 0;
}
In this example, we declare a C-style string and print it to the console. The output will be Hello, world!
.
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
std::cout << str;
return 0;
}
In this example, we declare a std::string and print it to the console. The output will be Hello, world!
.
In this tutorial, we've learned the differences between C-style strings and std::strings. C-style strings are simply arrays of characters terminated with a null character. On the other hand, std::strings are instances of a class that provides many functions to manipulate strings.
The next step in your learning could be to learn more about the string manipulation functions provided by the std::string class, and how you can perform similar operations with C-style strings. Here are some additional resources that you may find helpful:
Solution 1:
#include <iostream>
#include <string>
int main() {
char cstr[] = "Hello!";
std::string str = "Hello!";
std::cout << cstr << "\n" << str;
return 0;
}
In this solution, we declare both types of strings and print them. The output will be Hello!
twice.
Solution 2:
#include <iostream>
#include <string>
#include <cstring>
int main() {
char cstr[] = "Hello!";
std::string str = "Hello!";
std::cout << "C-style string size: " << strlen(cstr) << "\n";
std::cout << "std::string size: " << str.size();
return 0;
}
In this solution, we use the strlen
function from the cstring
library to get the size of the C-style string, and the size
method from the std::string class to get the size of the std::string. The output will be C-style string size: 6
and std::string size: 6
.