CとC++の文字列
このレッスンでは、長さの取得、連結、比較、検索の操作を通して、Cの文字配列とC++のstd::stringを比べます。
はじめに
Cは文章をcharの配列に保存し、その末尾には見えない文字'\0'が置かれます。配列に十分な空きがあるかはプログラマーが自分で保証しなければなりません。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は文字配列を直接扱う関数で、連結するときに配列が十分に大きくないと、バッファオーバーフロー(buffer overflow)を起こすことがあります。std::stringはsize()、+=、==、find()、substr()を備え、必要に応じて自動でメモリを広げるので、この問題を防げます。
C
Cは小さな手続き型の関数を使い、データがメモリ上でどう表されるかをそのまま見せます。
C++
C++は低レベルの操作もできるまま、ライブラリの型やより安全な抽象化を加えます。
発展問題
両方のバージョンを実行し、コードを書き換えて、それぞれの言語がもたらす安全性の違いを観察しましょう。
- 不正な入力や境界の値で試しましょう。
- 警告を増やすフラグ-Wall -Wextra -Wpedanticを付けてコンパイルしましょう。
- 共通の宣言はヘッダーファイルに、実装は別のファイルに分けましょう。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
- Count Uppercase Letters Count the capital letters in a text. 簡単
- Initials From a Name Build uppercase initials from a full name. 簡単
- Replace Spaces With Dashes Turn spaces into dashes to make a URL-style slug. 簡単