C/C++の基礎

C と C++ の文字列

C はテキストを見えない '\0' 文字で終わる char 配列に保存し、C++ はメモリを自動で管理する std::string で包みます。

C と C++ の文字列とは?

C はテキストを見えない '\0' 文字で終わる char 配列に保存し、C++ はメモリを自動で管理する std::string で包みます。

C の文字配列と C++ の std::string を比べます。長さ、連結、比較、検索。

重要なポイント

  • compiler warningを有効にしてすべて修正します。
  • 各値の型とlifetimeを把握します。
  • 入力と配列の境界を検証します。

CとC++のコード例

C
実行 →
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;
}
期待される出力
Ada has 3 letters
Ada Lovelace
equal: 1
ADA LOVELACE
contains "love": yes
C++
実行 →
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';
}
期待される出力
Ada has 3 letters
Ada Lovelace
equal: 1
ADA LOVELACE
contains "love": yes
first name: Ada

CとC++の比較

C では strlen、strcat、strcmp、strstr が生の配列を扱い、配列が十分大きいかは自分で確かめる必要があります。std::string には size()、+=、==、find()、substr() があり、自動で大きくなるのでバッファオーバーフローを避けられます。

C

Cは小さな手続き型APIと表現の詳細を明示します。

C++

C++は低レベルモデルを保ちつつ安全な型を追加します。

練習課題

両方を実行して変更し、言語ごとの保証を確認します。

  • 不正入力と境界値を追加します。
  • -Wall -Wextra -Wpedanticでコンパイルします。
  • 宣言と実装を分割します。

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ