C++字符串使用詳解

目錄

  • 字符串初始化
  • 字符串函數(shù)
    • 字符串大小,是否為空
    • 拼接
    • 插入
    • 找到子串位置
    • 字符串的遍歷
  • 字符串的替換

字符串初始化

  • 這是頭文件
#include <iostream>
using namespace std;
string s;
// 空串長(zhǎng)度為0
cout << s.size() << endl;

string s1 = "string";

string s2("string");

// s3 內(nèi)容為 666666
string s3(6, '6');

// 拷貝的是內(nèi)容
string s4 = s3;
s4[0] = '5';
// 輸出仍然是 666666
cout << s3 << endl;
// 輸出是 566666
cout << s4 << endl;

字符串的相關(guān)函數(shù)

  • 字符串大小,判空
string s = "string ";
// 字符串大小
s.size();
// 是否為空
bool b = s.empty();
  • 字符串拼接的幾種方式
string s = "string ";

string s1 = "this is a " + s;

s1 += s;

s1.append(s);

// 后面追加10個(gè)字符'a'
s1.append(10, 'a');
  • 插入
s.insert(0, "aaa");
  • 尋找子串位置
unsigned long index = s.find('s');

index = s.find("str");
  • 遍歷
for (char c: s) {
        cout << c << endl;
    }
for (int i = 0; i < s.size(); ++i) {
    cout << s1[i];
}

字符串的替換

string src_s = "abcdef";
string s1 = "0123456789";
// 首先參數(shù)擺出最長(zhǎng)的,后面就可以參考這個(gè)!!
src_s.replace(1, 2, s1, 3, 4);
/**
 * 這個(gè)表示 在原來(lái)的字符串 src_s 中的
 *  -> 1號(hào)位置 開始,加上這個(gè)位置往后的2個(gè)位置被替換掉,也就是替換掉 "bc" 被換掉
 *  -> 被替換的內(nèi)容是 s1串 的3號(hào)位置開始,加上這個(gè)位置往后的4個(gè)位置來(lái)替換,也就是 "3456"
 *  -> 結(jié)果就是 a3456def
 */

src_s = "abcdef";
// 后面少一個(gè)參數(shù),代表開始的位置是4號(hào),長(zhǎng)度就是剩余的全部長(zhǎng)度,這個(gè)時(shí)候的替換成的內(nèi)容是 456789 ,結(jié)果是 a456789def
src_s.replace(1, 2, s1, 4);
cout << src_s << endl;

// 將 bc 替換成 s1子串全部
src_s = "abcdef";
src_s.replace(1, 2, s1);
cout << src_s << endl;
  • 將子串替換成另外一個(gè)子串
void replace_sub_str(string &string1, string str1, string str2) {
    unsigned long i = string1.find(str1);
    // 如果找到子串,則開始替換
    while (i>=0 && i<string1.size()){
        string1.replace(i,str1.size(),str2);
        i = string1.find(str1);
    };
}


int main() {
    string s = "12123";
    replace_sub_str(s,"12","0");
    // 輸出003
    cout << s << endl;
    return 0;
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容