Strings in C++
-
What are Strings
A string in C++ is an object that represents a sequence of characters. It is stored as character arrays. On the end of string there is a null termination character
\0
. This is where compiler knows where the end is. -
How to write Strings
We can write strings on a many different ways. For example:
-
C style strings
We just create an array of chars and then we use" "
to write text.const char name[] = "lalala";
We could also use
const char*
because everithing in" "
is array. This pointer would point to first element of array.const char* name = "lalala";
-
Standard libray C++ string
We must include string from c++ standard libray using#include
and then we can use string class. Its basically like array of chars but it has some more functionality and it is much slower.#include <string> std::string name = "Lalalal";
-
-
Accessing string
If you are using C style strings you just use the name of variable to access all characters.
const char* name = "lalala"; name // its all characters
and if you need to get one character you use
[]
and index just like in arraysconst char* name = "lalala"; name[0] // 'l' // or you can use *name // because `name` is pointer to first character
If you are using string class you just use the name of variable.
std::string name = "lalala"; name // "lalala"
and if you need character from string class you use
at()
method and you specify indexstd::string name = "lalala"; name.at(5) // a