首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ string 類別完整指南:建構、存取、轉換、拼接與大小寫轉換

     編輯:關於C++

C++ string 類別優勢

C++ std::string 強化字串處理能力,可完全取代 C 風格的 char[] 與 char*。使用前需包含 <string> 標頭檔。

建構與初始化

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

int main() {
    string s1;                 // 空字串 ""
    string s2 = "c plus plus"; // 複製初始化
    string s3 = s2;            // 複製建構
    string s4(5, 's');         // "sssss" - 5 個 's'

    cout << s1 << s2 << s3 << s4 << endl;
    // 輸出: c plus plusc plus plussssss
    return 0;
}
  • s1:預設建構,內容為空字串(非 NULL)。
  • s2:由 C 字串初始化,結尾無 '\0',長度為實際字元數。
  • s3:複製建構,內容獨立。
  • s4(n, c):n 個字元 c 組成的字串。

長度查詢

string s = "c plus plus";
int len = s.length(); // 11
// 或 s.size(),兩者等價

因無結尾 \0,length() 回傳真實字元數。

轉換為 C 風格字串

string filename = "input.txt";
ifstream in;
in.open(filename.c_str()); // c_str() 回傳 const char*

// 複製部分內容到 char 陣列
char arr[50] = {0};
filename.copy(arr, 4, 0); // 從位置 0 複製 4 字元
cout << arr; // "inpu"

c_str() 回傳以 \0 結尾的 const char*,適合需 C API 的場合(如檔案操作、C 函式庫呼叫)。

輸入輸出操作

string s;
cin >> s;      // 讀取單一單字(遇空白、換行、Tab 停止)
cout << s << endl;

注意:operator>> 預設以空白字元為分隔符。若需讀取整行(含空白),請使用 getline(cin, s)。

字串拼接

string s1 = "alan", s2 = "jackson";
string s3 = s1 + s2;      // "alanjackson"
s3.append(" pray");       // "alanjackson pray"
s3 += "!";                // "alanjackson pray!"

查找與替換

string s1 = "apple google apple iphone";

// 查找首次出現位置
int idx = s1.find("google", 0); // 6

// 統計 "apple" 出現次數
int cnt = 0, pos = s1.find("apple", 0);
while (pos != string::npos) {
    ++cnt;
    pos += 5; // "apple".length()
    pos = s1.find("apple", pos);
}

// 替換第一個 "apple" → "jobs"
s1.replace(0, 5, "jobs");

// 替換所有 "apple" → "jobs"
pos = s1.find("apple", 0);
while (pos != string::npos) {
    s1.replace(pos, 5, "jobs");
    pos += 4; // "jobs".length()
    pos = s1.find("apple", pos);
}

刪除與插入

string s1 = "apple google apple iphone";

// 刪除首個 'g'
auto it = find(s1.begin(), s1.end(), 'g');
s1.erase(it); // 僅刪除單一字元

// 開頭/結尾插入
s1.insert(0, "macos ");
s1.insert(s1.length(), " facebook");

大小寫轉換

#include <algorithm>
#include <cctype>

string s1 = "JASON";
// 轉小寫
transform(s1.begin(), s1.end(), s1.begin(), ::tolower); // "jason"
// 轉大寫
transform(s1.begin(), s1.end(), s1.begin(), ::toupper); // "JASON"

transform 以單字元函式 tolower/toupper 轉換各字元,原地修改。

常用成員函式速查

函式說明
length() / size()字串長度
empty()是否為空
c_str()轉 const char*
operator[] / at()存取字元(at() 有邊界檢查)
find() / rfind()正向/反向查找子串
substr(pos, len)擷取子串
replace(pos, len, str)替換區間
insert(pos, str)插入字串
erase(pos, len)刪除區間
append(str) / +=尾部拼接
compare(str)字典序比較

總結

std::string 提供豐富、安全、高效的字串操作介面,應作為 C++ 專案的首選字串型別。善用 const string& 作為函式參數可避免不必要拷貝,配合 move 語意(C++11)可進一步優化效能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved