0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

stringを知りました

0
Last updated at Posted at 2026-04-06

C++の string 型を「char との関係」から理解する

C++を学んでいて出た疑問があります.

string って結局なんなの?
charchar[] と何が違うの?

この記事では

  • char
  • char[]
  • string

の関係を整理します.

プログラミング初心者の書く記事なので間違いがあったらご指摘ください.


まず結論

string は

「charの配列を安全, 便利に扱うためのクラス」

中身は char の並び .


char とは

char c = 'A';

char1バイトの整数型 .

'A' → 65 (ASCIIコード)

つまり

char = 数値


char を並べると「文字列」になる

char s[6] = {'H','e','l','l','o','\0'};

メモリ上の並び

| H | e | l | l | o | \0 |

最後の \0 は「文字列の終わり」を示す印です.
これを ヌル終端文字 と呼びます.


C言語の文字列の正体

C言語には string 型は存在しません.

char s[] = "Hello";

これは内部的に

{'H','e','l','l','o','\0'}

になっています.

つまり

C言語の文字列 = char の配列


ここで問題が発生する

C言語の文字列は

  • 長さを自分で管理する
  • コピーも自分で行う
  • 結合も自分で行う
  • メモリも自分で管理する

すべて手動で初心者にとってはかなり危険な操作になります.


そこで登場するのが string

#include <string>
using namespace std;

string s = "Hello";

これは

char配列を内部に持つクラス

です.

string = charの動的配列 + 長さ情報 + 便利な関数


メモリの違い

char配列

char s[6] = "Hello";
  • サイズ固定
  • スタック領域
  • 手動管理

string

string s = "Hello";
  • サイズ可変
  • ヒープ領域
  • 自動管理

文字列結合の違い

char配列

strcat(a, b);

危険, 面倒

string

string c = a + b;

安全, 簡単

内部で新しい char 配列を確保してコピーしています.


出た疑問点

疑問点1: string は特別な文字型なのか?

ではなくchar の塊です.

疑問点2: char[] と string は別物なのか?

本質は同じです. 扱い方が違うだけです.

疑問点3: string は遅いのか?

ほとんど問題にならないです.
安全性と可読性が圧倒的に高いです.


まとめ

char = 1文字 (数値)
char[] = 文字の並び (C言語の文字列)
string = char[] を安全に扱うためのクラス

string はただの文字列型ではなくchar配列の延長

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?