AnyCompiler

Strings

std::string es un tipo de string real, owned y mutable — concatenar con + construye un nuevo string, y .length() reporta su tamaño. A diferencia de la división de Rust entre un String owned y un &str prestado, C++ solo tiene un tipo de string, pasado por value o por reference según se necesite.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string first = "Hello";
    string second = "World";
    string combined = first + ", " + second + "!";
    cout << combined << endl;
    cout << "length = " << combined.length() << endl;
    return 0;
}
Output
Hello, World!
length = 13

Substrings

s.substr(start, length) devuelve un nuevo string que contiene length caracteres empezando en el índice start.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s = "C++ Programming";
    string sub = s.substr(4, 11);
    cout << sub << endl;
    return 0;
}
Output
Programming

Siguiente: structs y classes — agrupar datos relacionados, y la única diferencia entre struct y class.

Practice exercise

Dado string s = "rust lang", usa substr para extraer solo "rust" (los primeros 4 caracteres), luego imprímelo.