c++ 11 string literal code example

Example 1: string literals in c++

#include <iostream>
#include <string>
#include <stdlib.h>// using c standard library
int main()
{

	"Caleb";//String literal is a series of characters between two double quotes
	//It is a const char array and array is  just a ptr to a begining of block of memory
	//String literals are stored in read only section of memory

	const char name[8] = "Rhe\0eno";// \0 is null termination character
	std::cout << strlen(name) << std::endl;//c function for size of string ,output => 3 due to null terminating char \0
	std::cout << name << std::endl;// output => Rhe because null termination char \0

	const char* name1 = u8"Caleb";//1 byte per char
	const wchar_t* name2 = L"Caleb";//is 2 or 4 bytes per character dependent on compile on windows it's usually 2bytes but on linux it is 4 bytes per char
	const char16_t* name3 = u"Caleb";//2 byte per char
	const char32_t* name4 = U"Caleb";//4 byte per char


	using namespace std::string_literals;
	// this name space give   number of functions for convenience

	//std::string name0 = "Caleb" + "hello";//error because can't add ptr to ptr
	std::string name0 = "Caleb"s + "hello";//s is an operator that returns std::string this will work because now adding a ptr to actual string
	//various versions of strings
	std::wstring namee = L"Caleb"s + L"hello";//wide string: 2 or 4 bytes depend on compiler
	std::u32string namee32 = U"Caleb"s + U"hello";//u 32 string :4 bytes per char
	std::u16string namee16 = u"Caleb"s + u"hello";//u16 string :2bytes per char
	std::string namee8 = u8"Caleb";//1 byte per character
	const char* example = R"(Line1
Line 2
Line 3 
Line 4 
)";//R:Raw  for writing on different lines it prints escape characters 
	std::cin.get();

};

Example 2: c++ raw string

//EXAMPLE
std::string sRaw = R"(aaa\ttt %)";     //   aaa/ttt %
std::string sNonRaw = "aaa\ttt %";   //     aaa     tt %
std::cout << sRaw << "\n";
std::cout << sNonRaw << "\n";

//SYNTAX
// R"(<string-with-raw-values>)"
// R"(...)"

Tags:

Cpp Example