// ===== CodeLab: C++ string 字符串处理 =====
// 来源: https://aoerliang.dpdns.org/articles/cpp-string
// 以下代码片段按文章出现顺序拼接, 共 5 段

// ----- 片段 1 (cpp) -----
#include <string>
using namespace std;

string s1 = "hello";          // 字面量构造
string s2(5, 'a');            // "aaaaa"
string s3 = s1 + " world";    // 拼接:"hello world"

s3.push_back('!');            // 尾部加字符
s3 += "!!";                   // 追加字符串
int n = s3.length();          // 长度(与 size() 相同)
bool empty = s3.empty();
char c = s3[0];               // 下标访问,越界不检查
char c2 = s3.at(1);           // 越界抛 out_of_range

// ----- 片段 2 (cpp) -----
string a = "abc", b = "abd";
if (a < b) { /* abc 排在 abd 前面 */ }

// 字符串与数字混拼
int score = 95;
string msg = "分数: " + to_string(score);

// ----- 片段 3 (cpp) -----
string s = "hello world, hello cpp";

size_t pos = s.find("world");     // 返回下标 6
if (pos != string::npos) {        // npos 表示"没找到"
    string sub = s.substr(6, 5);  // 从 6 开始取 5 个字符:"world"
}

// 反向查找、查找任一字符
size_t last = s.rfind("hello");   // 13
size_t comma = s.find_first_of(",;!");  // 11

// 用 find 循环统计子串出现次数
int cnt = 0;
pos = s.find("hello");
while (pos != string::npos) {
    ++cnt;
    pos = s.find("hello", pos + 1);
}

// ----- 片段 4 (cpp) -----
#include <string>
using namespace std;

// 数字 → 字符串
string a = to_string(3.14);   // "3.140000"
string b = to_string(42);     // "42"

// 字符串 → 数字(C++11 起,失败抛异常)
int i = stoi("42");           // 42
long l = stol("123456789");
double d = stod("3.14");
float f = stof("2.5f");

// 带进制解析
int hexv = stoi("ff", nullptr, 16);   // 255

// ----- 片段 5 (cpp) -----
// C++ → C:只读,别修改返回值指向的内容
const char* cstr = s.c_str();

// C++ → C:可写副本
vector<char> buf(s.begin(), s.end());
buf.push_back('\0');          // C 字符串需要结尾 '\0'
char* writable = buf.data();

// C → C++:直接构造
const char* old = "from c";
string now(old);
