New blog location
New blog location
\0
, so that code that uses the string knows where it ends. The space needed for a string is always one more than the number of readable characters.char *str = "world"; str[0] = 'y'; //undefined behavior
const char*
, the compiler will catch attempts to modify string literals:const char * str = "world"; str[0] = 'k'; //compiler will flag this as error.
char str[] = "hello world"; str[0] = 'y';
const char* str = R"(Brave New World)"; const char* str = R"(Line1: Brave Line2: New World)";
)
or (
in raw string literals, use unique delimiter sequences like the following:const char* str = R"-(Embedded ) parens)-";
string
has +
operator overloaded to mean concatenation. So the following produces hello world
:string one("hello"); string two("world"); string final; final = one + " " + two;
==
, !=
, <
, etc are all overloaded so they use the actual string characters. For compatibility one can call c_str()
to return a C style string, but this should be the last operation and should never be done an stack allocated string
. Because string literals are inferred as const char*
, one can use s
to interpret a string literal as std::string
:auto myStr = "hello brave world"s;
std
namespace has several functions to convert numbers into strings. Examples : string to_string(int vaL)
and string to_string(double val)
. To convert from strings to numbers, use functions such as int stoi(const string& s, size_t *idx = 0, int base=10)
. Example:const string toConvert = " 123ABC"; size_t index = 0; int value = stoi(toConvert,&index); //index will be the index of 'A'.
string_view
is a readonly string
but without the overhead of a const string&
. It doesn't copy strings. To concatenate a string_view
with a string, use the data()
member function:string str = "Hard"; string_view sview = " Rock"; auto result = str + sview.data();
string_view
s into functions, pass them by value. For string_view
literals, use "sv":auto sview = "Sample string view"sv;
string_view extractLastDelimitedElement(string_view sv, char delimiter) { return sv.substr(sv.rfind(delimiter)); }
Comments
Post a Comment