天天看点

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");
}           

继续阅读