月ノ書

【C++】文字列を使いこなす|C文字列とstd::stringの基本操作と注意点

この記事でわかること

この記事では、C++での 文字列の扱い方 を解説します

  • C文字列(C言語的文字列)の使い方
  • std::string の基本と便利な操作
  • 文字列を扱う際の注意点

文字列とは

文字列とは 文字が並んだデータ のことで、C++では大きく分けて2種類あります

1. C文字列

2. std::string

C文字列の基本

C文字列は char[] とヌル文字で表現されます。初心者はバグりやすいので注意が必要です

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

int main() {
    char str[20] = "Hello";
    cout << str << endl;

    strcat(str, " World");   // 文字列を連結
    cout << str << endl;

    cout << "length = " << strlen(str) << endl;

    return 0;
}
Hello
Hello World
length = 11

std::string の基本操作

C++では std::string を使うのが推奨です

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

int main() {
    string s = "Hello";
    cout << s << endl;

    s += " World";           // 文字列を連結
    cout << s << endl;

    cout << "length = " << s.size() << endl     // 長さ取得
         << "substr = " << s.substr(0, 5) << endl  // 部分文字列取得
         << "find = " << s.find("World") << endl   // 検索(インデックスを返す)
         ;

    return 0;
}
Hello
Hello World
length = 11
substr = Hello
find = 6

文字列の入力方法

C++で文字列を入力する場合、std::cinstd::getline の違いに注意が必要です

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

int main() {
    string name;
    cout << "名前を入力してください: ";
    getline(cin, name);   // スペースを含む入力も可能

    cout << "こんにちは, " << name << " さん!" << endl;
    return 0;
}
名前を入力してください: 山田 太郎
こんにちは, 山田 太郎 さん!

まとめ

学習進捗

0
Would love your thoughts, please comment.x