Strings
Along with the C way of using strings as character arrays there are many other new things in C++.
String class
The standard C++ library provides a string class type which allows you to work with string just like in Java. By adding the s suffix teh string literal becomes a C++ string.
#include <iostream>
#include <string>
using namespace std;
int main() {
auto name = "George"s;
cout << "size: " << name.size() << endl;
cout << "length: " << name.length() << endl;
cout << "name[2]: " << name[2] << endl;
cout << "c_str: " << name.c_str() << endl;// conver to null terminated C string
cout << "substr: " << name.substr(1, 3) << endl;
}
String_View class
The string_view
class is a good way to pass C strings between methods because all it is, is a wrapper for the size and the char array.
String types
In C++ there are lots of ways of creating strings from special representations.
#include <iostream>
using namespace std;
int main() {
cout << "1 byte: " << "abcd" << endl;
cout << "2 byte wide: " << L"abcd" << endl;
cout << "UTF-8: " << u8"abcd" << endl;
cout << "UTF-16: " << u"abcd" << endl;
cout << "UTF-32: " << U"abcd" << endl;
}
Output
Raw string literals
Often times you want to be able to use backslashes and double quotes in a string litral which can get very annoying with escaping it. In C++ you can create raw litrals which accepts everything between the marker and round brackets.
#include <iostream>
#include <string>
using namespace std;
int main() {
string text = R"---(This is very "funny"
I can write whatever I want \\\\\\)---";
cout << text << endl;
}
Output