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()<
删除字符
//找到指定字符,然后删除
void main() {
    string s1 = "hello1 hello2 hello3";
    string ::iterator it = find(s1.begin(), s1.end(), '1');
    if (it != s1.end()) {
        s1.erase(it);
    }
    cout << "删除之后:"<
插入字符
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");
}

你可能感兴趣的:(12.C++ string 操作)