天天看點

12.C++ string 操作

字元串初始化
void main() {
    string s1 = "111111";
    string s2("22222");
    string s3 = s2;
    cout << s1<< endl;
    cout << s2 << endl;
    cout << s3 << endl;
}           
字元串周遊

使用[]和使用at()周遊的差别在于,at()發生數組越界會抛出異常,可以捕獲,但是[]方式發生異常無法進行捕獲

//通過角标取值
void main() {
    string  s1 = "abcdefg";
    for (int i = 0; i < s1.length(); i++){
        cout << s1[i];
    }
}

//通過at()取值
void main() {
    string  s1 = "abcdefg";
    for (int i = 0; i < s1.length(); i++){
        cout << s1.at(i);
    }
}

//使用疊代器周遊
void main() {
    string  s1 = "abcdefg";
    for (string::iterator i = s1.begin(); i != s1.end(); i++) {
        //疊代器可以看作指針
        cout << *i<< endl;
    }
}           
string char的轉換
void main(){
    string s1 = "aaabbbccc";
    // to char
    cout << s1.c_str()<<endl;
    char buf[128] = {0};
    s1.copy(buf, 9, 0);
    cout <<"buf="<< buf<< endl;
}           
string連結
void main() {
    string s2 = "aaa";
    string s3 = "bbb";
    s2 = s2 + s3;
    cout << "s2 = "<<s2<< endl;

    string s4 = "222";
    string s5 = "444";
    s4.append(s5);
    cout << "s4="<<s4<< endl;
}           
查找和替換
void main() {
    string s = "who are you and who is she and who am i";
        //從0開始查找
    int index = s.find("who", 0);
    while (index != string::npos) {
        cout << "index="<<index << endl;
        //替換,從0開始,替換三個字元
        s.replace(index, 3, "WHOSE");
        index = index + 1;
        index = s.find("who", index);
    }
    cout << "替換後:"<<s << endl;
}           
删除字元
//找到指定字元,然後删除
void main() {
    string s1 = "hello1 hello2 hello3";
    string ::iterator it = find(s1.begin(), s1.end(), '1');
    if (it != s1.end()) {
        s1.erase(it);
    }
    cout << "删除之後:"<<s1<< endl;
    system("pause");
}

//删除指定範圍的字元
void main() {
    string s1 = "hello1hello2hello3";
    s1.erase(1, 5);
    cout << "删除1到5位置的字元後:" << s1 << endl;
    system("pause");
}           
插入字元
void main() {
    string s1 = "how are you today";
    s1.insert(0, "hello ");
    cout << "插入後:" << s1 << endl;
    system("pause");
}           
大小寫轉換
void main() {
    string s1 = "how are you today";
    transform(s1.begin(), s1.end(), s1.begin(), toupper);
    cout << "轉換後:" << s1 << endl;
    string s2 = "I AM GOOD";
    transform(s2.begin(), s2.end(), s2.begin(), tolower);
    cout << "轉換後:" << s2 << endl;
    system("pause");
}           

繼續閱讀