What is std::basic_string::basic_string in C/C++?
The basic_string class is a generalized class that provides many functional operations on strings like searching, sorting, copying, clearing, concatenation, conversion, comparisons, and more.
The class definition and all utility functionalities are provided by namespace std, e.g., the typedef statements.
The basic_string class supports the following character sets:
charwchar_t
basic_string requires a header file:
#include <string>
string
A string is a specialized instance of the basic_string class with type char.
//typedef in namespace std
typedef basic_string<char> string
Code
#include <iostream>#include <string>using namespace std;int main() {//declare a stringstring str("I love chicks"); //calling constructor//print string and its lengthcout<<str<<endl<<str.length()<<endl;//declare anothor stringstring str2=str; //assignment operator of string classstr2+=" and goats"; //contatenationcout<<str2<<endl<<str2.length()<<endl;return 0;}
wstring
This is a specialized instance of the basic_string class with type wchar_t.
//typedef in namespace std
typedef basic_string<wchar_t> wstring
Note: Type
wchar_tcommonly represents Unicode, but the standard does not specify its size and is implementation-defined. C++ 11 has also support for typeschar16_tandchar32_t. Visit www.unicode.org for more detail on the Unicode Standard.
Code
#include <iostream>#include <string>using namespace std;int main() {//declare a wide character stringwstring str(L"programming is fun");//declare anothor wstringwstring str1=(L"traveling is fun");//contatenationwstring str2= str+ L" and "+str1;//wcout is a output stream oriented to wide characters//wchar_twcout<<str<<endl<<str1<<endl<<str2<<endl;//size of character in terms of byteswcout<<sizeof(wchar_t)<<endl;return 0;}
Unlike
charstrings,stringsare not necessarily null-terminated.