S SmartDocs
Serie: C++ cpp 225 righe · Aggiornato 2026-04-03

std_string.cpp

C++/Part1_基礎入門/Ch05_陣列與字串/std_string.cpp

// ============================================================
// Ch05 — std::string 字串操作
// 編譯:g++ -std=c++17 -Wall -o std_string std_string.cpp
// ============================================================

#include <iostream>
#include <string>

int main() {
    std::cout << "===== Ch05:std::string =====\n\n";

    // ── 1. 建構方式 ──
    std::cout << "【1】建構方式\n";

    std::string s1;                         // 空字串
    std::string s2 = "Hello";              // 從 C 字串
    std::string s3("World");               // 直接初始化
    std::string s4(5, '*');                // 重複字元:"*****"
    std::string s5(s2);                    // 複製建構
    std::string s6(s2, 1, 3);             // 子字串:"ell"
    std::string s7 = s2 + ", " + s3;      // 串接

    std::cout << "s1 (空)      = \"" << s1 << "\"\n";
    std::cout << "s2           = \"" << s2 << "\"\n";
    std::cout << "s3           = \"" << s3 << "\"\n";
    std::cout << "s4 (5個*)    = \"" << s4 << "\"\n";
    std::cout << "s5 (複製s2)  = \"" << s5 << "\"\n";
    std::cout << "s6 (子字串)  = \"" << s6 << "\"\n";
    std::cout << "s7 (串接)    = \"" << s7 << "\"\n\n";

    // ── 2. 串接(Concatenation) ──
    std::cout << "【2】串接\n";

    std::string first = "C++";
    std::string second = "程式設計";

    // 用 + 運算子
    std::string combined = first + " " + second;
    std::cout << "用 +   :\"" << combined << "\"\n";

    // 用 append
    std::string result = first;
    result.append(" 是很棒的語言");
    std::cout << "append :\"" << result << "\"\n";

    // 用 +=
    std::string msg = "學習";
    msg += " C++";
    msg += " 真有趣!";
    std::cout << "+=     :\"" << msg << "\"\n\n";

    // ── 3. 比較 ──
    std::cout << "【3】比較\n";

    std::string a = "apple";
    std::string b = "banana";
    std::string c = "apple";

    std::cout << "\"apple\" == \"apple\"  → " << (a == c ? "true" : "false") << "\n";
    std::cout << "\"apple\" != \"banana\" → " << (a != b ? "true" : "false") << "\n";
    std::cout << "\"apple\" <  \"banana\" → " << (a < b ? "true" : "false") << "\n";
    std::cout << "\"apple\".compare(\"apple\") = " << a.compare(c) << "\n\n";

    // ── 4. 搜尋(find / rfind) ──
    std::cout << "【4】搜尋\n";

    std::string text = "Hello World, Hello C++!";
    std::cout << "文本:\"" << text << "\"\n";

    // find — 從前往後搜尋
    size_t pos1 = text.find("Hello");
    std::cout << "find(\"Hello\")     = " << pos1 << "\n";

    // 從指定位置開始搜尋
    size_t pos2 = text.find("Hello", pos1 + 1);
    std::cout << "find(\"Hello\", 1+) = " << pos2 << "\n";

    // rfind — 從後往前搜尋
    size_t pos3 = text.rfind("Hello");
    std::cout << "rfind(\"Hello\")    = " << pos3 << "\n";

    // 找不到的情況
    size_t pos4 = text.find("Python");
    std::cout << "find(\"Python\")    = ";
    if (pos4 == std::string::npos) {
        std::cout << "npos(找不到)\n";
    } else {
        std::cout << pos4 << "\n";
    }

    // 搜尋單一字元
    size_t pos5 = text.find('W');
    std::cout << "find('W')         = " << pos5 << "\n\n";

    // ── 5. 子字串(substr) ──
    std::cout << "【5】子字串 substr\n";

    std::string full = "Hello, World!";
    std::cout << "原始:\"" << full << "\"\n";

    std::string sub1 = full.substr(0, 5);    // 從位置 0 取 5 個字元
    std::string sub2 = full.substr(7);       // 從位置 7 到結尾
    std::string sub3 = full.substr(7, 5);    // 從位置 7 取 5 個字元

    std::cout << "substr(0, 5) = \"" << sub1 << "\"\n";
    std::cout << "substr(7)    = \"" << sub2 << "\"\n";
    std::cout << "substr(7, 5) = \"" << sub3 << "\"\n\n";

    // ── 6. 替換、插入、刪除 ──
    std::cout << "【6】replace / insert / erase\n";

    std::string original = "Hello World";
    std::cout << "原始    :\"" << original << "\"\n";

    // replace
    std::string replaced = original;
    replaced.replace(6, 5, "C++");
    std::cout << "replace :\"" << replaced << "\"\n";

    // insert
    std::string inserted = original;
    inserted.insert(5, ",");
    std::cout << "insert  :\"" << inserted << "\"\n";

    // erase
    std::string erased = original;
    erased.erase(5, 6);  // 刪除位置 5 開始的 6 個字元
    std::cout << "erase   :\"" << erased << "\"\n\n";

    // ── 7. 長度與容量 ──
    std::cout << "【7】長度與容量\n";

    std::string sample = "Hello";
    std::cout << "length()   = " << sample.length() << "\n";
    std::cout << "size()     = " << sample.size() << "\n";
    std::cout << "capacity() = " << sample.capacity() << "\n";
    std::cout << "empty()    = " << (sample.empty() ? "true" : "false") << "\n";

    sample.clear();
    std::cout << "clear 後 empty() = " << (sample.empty() ? "true" : "false") << "\n\n";

    // ── 8. 存取字元 ──
    std::cout << "【8】存取字元\n";

    std::string word = "Hello";
    std::cout << "word = \"" << word << "\"\n";
    std::cout << "word[0]    = '" << word[0] << "'\n";
    std::cout << "word.at(1) = '" << word.at(1) << "'\n";
    std::cout << "front()    = '" << word.front() << "'\n";
    std::cout << "back()     = '" << word.back() << "'\n";

    // 修改字元
    word[0] = 'h';
    std::cout << "word[0]='h' → \"" << word << "\"\n\n";

    // ── 9. 走訪字串 ──
    std::cout << "【9】走訪字串\n";

    std::string str = "C++17";

    // 索引走訪
    std::cout << "索引走訪:";
    for (size_t i = 0; i < str.size(); i++) {
        std::cout << str[i] << ' ';
    }
    std::cout << "\n";

    // 範圍 for
    std::cout << "範圍 for :";
    for (char ch : str) {
        std::cout << ch << ' ';
    }
    std::cout << "\n";

    // 迭代器
    std::cout << "迭代器   :";
    for (auto it = str.begin(); it != str.end(); ++it) {
        std::cout << *it << ' ';
    }
    std::cout << "\n\n";

    // ── 10. 數值轉換 ──
    std::cout << "【10】數值轉換\n";

    // 數值 → 字串
    int num = 42;
    double pi = 3.14159;
    std::string numStr = std::to_string(num);
    std::string piStr  = std::to_string(pi);
    std::cout << "to_string(42)      = \"" << numStr << "\"\n";
    std::cout << "to_string(3.14159) = \"" << piStr << "\"\n";

    // 字串 → 數值
    std::string intStr = "12345";
    std::string dblStr = "3.14";

    int parsedInt    = std::stoi(intStr);
    double parsedDbl = std::stod(dblStr);
    long parsedLong  = std::stol("9999999999");

    std::cout << "stoi(\"12345\")       = " << parsedInt << "\n";
    std::cout << "stod(\"3.14\")        = " << parsedDbl << "\n";
    std::cout << "stol(\"9999999999\")  = " << parsedLong << "\n\n";

    // ── 11. 實用範例:分割字串 ──
    std::cout << "【11】實用範例:用 find + substr 分割字串\n";

    std::string csv = "Alice,Bob,Charlie,Diana";
    std::cout << "原始:\"" << csv << "\"\n";
    std::cout << "分割結果:\n";

    std::string delimiter = ",";
    std::string temp = csv;
    size_t pos = 0;
    int index = 0;

    while ((pos = temp.find(delimiter)) != std::string::npos) {
        std::string token = temp.substr(0, pos);
        std::cout << "  [" << index++ << "] \"" << token << "\"\n";
        temp.erase(0, pos + delimiter.length());
    }
    std::cout << "  [" << index << "] \"" << temp << "\"\n";

    return 0;
}

Articoli correlati