Skip to content

Strings

Strings

std::string is a safe container for char strings of dynamic size.

It automatically coordinates the process of allocating and deallocating memory for the elements as required.

1
#include <string>

1
2
// Strings are dynamic arrays of chars
std::string str = "avocado";

1
std::cout << str << '\n';

1
2
3
for (size_t i = 0; i < str.size(); ++i) {
    std::cout << "str[" << i << "]: " << str[i] << '\n';
}

1
2
3
4
5
if (str.size() >= 10) {
    std::cout << "str[10]: " << str[10] << '\n';
} else {
    std::cout << "str[10]: (does not exist)" << '\n';
}

1
2
3
4
std::cout << "str.size(): " << str.size() << '\n';
std::cout << "str.empty(): " << str.empty() << '\n';
std::cout << "str.front(): " << str.front() << '\n';
std::cout << "str.back(): " << str.back() << '\n';

1
2
std::cout << "&str: " << &str << '\n';
std::cout << "str.data(): " << str.data() << '\n';

1
2
3
std::cout << "str[0]: " << str[0] << '\n';
std::cout << "str[1]: " << str[1] << '\n';
std::cout << "str[2]: " << str[2] << '\n';

1
2
3
std::cout << "&str[0]: " << &str[0] << '\n';
std::cout << "&str[1]: " << &str[1] << '\n';
std::cout << "&str[2]: " << &str[2] << '\n';

Share Snippets