Fondamenti di C/C++

Stringhe in C e C++

Il C salva il testo in array di char che terminano con un carattere '\0' nascosto, mentre il C++ lo avvolge in std::string, che gestisce la memoria per te.

Che cos’è Stringhe in C e C++?

Il C salva il testo in array di char che terminano con un carattere '\0' nascosto, mentre il C++ lo avvolge in std::string, che gestisce la memoria per te.

Confronta gli array di caratteri del C con std::string del C++: lunghezza, unione, confronto e ricerca.

Punti importanti

  • Abilita i warning del compilatore e correggili.
  • Conosci tipo e lifetime di ogni valore.
  • Valida input e limiti degli array.

Esempi di codice C e C++

C
Esegui →
main.c
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void) {
    /* A C string is a char array that ends with '\0'. */
    char name[32] = "Ada";
    printf("%s has %zu letters\n", name, strlen(name));

    /* strcat appends; the array must have room for the result. */
    strcat(name, " Lovelace");
    printf("%s\n", name);

    /* strcmp returns 0 when two strings are equal. */
    printf("equal: %d\n", strcmp("cat", "cat") == 0);

    /* Walk the characters until the terminating '\0'. */
    char upper[32];
    size_t i = 0;
    for (; name[i] != '\0'; i++) {
        upper[i] = (char)toupper((unsigned char)name[i]);
    }
    upper[i] = '\0';
    printf("%s\n", upper);

    /* strstr finds a substring and returns a pointer to it, or NULL. */
    printf("contains \"love\": %s\n", strstr("lovelace", "love") ? "yes" : "no");
    return 0;
}
Output previsto
Ada has 3 letters
Ada Lovelace
equal: 1
ADA LOVELACE
contains "love": yes
C++
Esegui →
main.cpp
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>

int main() {
    // std::string manages its own memory and grows as needed.
    std::string name = "Ada";
    std::cout << name << " has " << name.size() << " letters\n";

    name += " Lovelace";
    std::cout << name << '\n';

    // == compares the contents of two strings.
    std::cout << "equal: " << (std::string("cat") == "cat") << '\n';

    std::string upper = name;
    std::transform(upper.begin(), upper.end(), upper.begin(),
                   [](unsigned char c) { return static_cast<char>(std::toupper(c)); });
    std::cout << upper << '\n';

    // find returns std::string::npos when the text is missing.
    std::string word = "lovelace";
    std::cout << "contains \"love\": " << (word.find("love") != std::string::npos ? "yes" : "no") << '\n';
    std::cout << "first name: " << name.substr(0, 3) << '\n';
}
Output previsto
Ada has 3 letters
Ada Lovelace
equal: 1
ADA LOVELACE
contains "love": yes
first name: Ada

Confronto tra C e C++

In C, strlen, strcat, strcmp e strstr lavorano su array grezzi e tocca a te assicurarti che l'array sia abbastanza grande. std::string offre size(), +=, ==, find() e substr() e cresce da solo, evitando i buffer overflow.

C

C espone piccole API procedurali e dettagli di rappresentazione.

C++

C++ mantiene il modello low-level aggiungendo tipi più sicuri.

Esercizi pratici

Esegui entrambe le versioni e modificale per osservare le diverse garanzie.

  • Aggiungi input non validi e valori limite.
  • Compila con -Wall -Wextra -Wpedantic.
  • Separa dichiarazioni e implementazione.

Esercitati con una sfida

Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.

Tutte le sfide