主なインターフェース
コンストラクタ
| 関数名 | 機能 |
| string() | 空の文字列オブジェクトを生成 |
| string(const char* s) | C文字列から文字列オブジェクトを生成 |
| string(size_t n, char c) | n個の文字cで構成される文字列を生成 |
| string(const string& s) | コピーコンストラクタ |
void test1() {
string str1; // 空の文字列を生成
cout << "str1 = " << str1 << endl;
const char* cstr = "Hello World!";
string str2(cstr); // C文字列をstringに変換
cout << "str2 = " << str2 << endl;
string str3(str2); // コピーコンストラクタ使用
cout << "str3 = " << str3 << endl;
string str4(10, 'a');
cout << "str4 = " << str4 << endl;
}
容量操作
| 関数名 | 機能 |
| size | 有効文字数を返す |
| capacity | 確保された容量を返す |
| reserve(size_t n) | 容量をnに予約 |
| resize(size_t n, char c) | 文字数をnに調整し、不足分をcで埋める |
void test2() {
string s("初期データ");
cout << "サイズ: " << s.size() << endl;
cout << "容量: " << s.capacity() << endl;
s.reserve(100);
cout << "予約後の容量: " << s.capacity() << endl;
s.resize(15, 'X');
cout << "拡張後のサイズ: " << s.size() << endl;
}
アクセスと反復
void test3() {
string str("Hello C++");
for(size_t i = 0; i < str.size(); ++i) {
str[i] = toupper(str[i]);
}
cout << str << endl;
string::iterator it = str.begin();
while(it != str.end()) {
cout << *it++ << " ";
}
}
挿入と削除
| 関数名 | 機能 |
| push_back(char c) | 末尾に文字を追加 |
| insert(size_t pos, const string& str) | 指定位置に文字列を挿入 |
| erase(size_t pos, size_t n) | 指定位置からn文字を削除 |
探索と置換
void test4() {
string s("C++プログラミング言語");
size_t pos = s.find("プログラミング");
if(pos != string::npos) {
s.replace(pos, 11, "プログラミング");
}
cout << s << endl;
}
カスタム実装例
namespace custom_string {
class basic_string {
public:
explicit basic_string(const char* str = "")
: length(0), capacity(0), data(nullptr) {
// 実装詳細
}
// 演算子オーバーロード
basic_string& operator=(const basic_string& other) {
// 代入演算子の実装
}
// その他のメンバ関数
private:
size_t length;
size_t capacity;
char* data;
};
}