C++ · std::string
std::string versus C strings, common operations (substr, find, append, compare), mutability, and converting numbers.
std::string is the C++ string class, and it’s far easier to use than raw char* C strings. Differences from Python I noticed:
- It is mutable, so
s[0] = 'p'works. substr(pos, len)takes a length, not an end index.findreturnsstd::string::nposwhen nothing is found.+and+=concatenate.std::to_string(n)andstd::stoi(s)convert between numbers and strings.- Comparing with
==compares the contents, which isn’t true for C-string pointers.
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
int main() {
std::string s = "Pandit Deendayal Energy University";
std::cout << s.size() << " chars, first word: " << s.substr(0, s.find(' ')) << '\n';
auto pos = s.find("Energy");
std::cout << "Energy at " << pos << '\n';
std::cout << "missing: " << (s.find("Python") == std::string::npos) << '\n';
s[0] = 'p'; // mutable
std::string upper = s;
std::transform(upper.begin(), upper.end(), upper.begin(),
[](unsigned char c) { return std::toupper(c); });
std::cout << s << "\n" << upper << '\n';
std::string id = "ICT" + std::to_string(2023);
int year = std::stoi("2027");
std::cout << id << ", graduating " << year << ", equal? " << (id == "ICT2023") << '\n';
}
Output:
34 chars, first word: Pandit
Energy at 17
missing: 1
pandit Deendayal Energy University
PANDIT DEENDAYAL ENERGY UNIVERSITY
ICT2023, graduating 2027, equal? 1Sources
- std::basic_string — cppreference.com
- Introduction to std::string — LearnCpp.com
- std::to_string — cppreference.com