c++ string使用

2024-01-09  本文已影响0人  简书网abc
// #include "lib/sundry.hpp"
#include <future>
#include <iostream>

using namespace std;

void test01() {
    string str1("hello world");
    cout << str1 << endl;

    string str2(5, 'a');
    cout << str2 << endl;

    string str4;
    str4 = "hello world!";
    cout << str4 << endl;
    str4 = 'w';
    cout << str4 << endl;

    string str5 = "hello world";
    str4.assign(str5, 2, 3);    // string成员函数
    cout << str4 << endl;
    cout << "test01 end ... " << endl;
}

void test02() {
    string str1 = "hello world";
    cout << str1[1] << " -- " << str1.at(6) << endl;
    str1[1] = 'E';              // []越界不会抛出异常.
    str1.at(6) = 'H';           // at方法,越界会抛出异常.
    cout << str1 << endl;
    
    try{
//        str1[100] = 'a';
        str1.at(100) = 'a';         // 字符串异常捕获.
    } catch (exception &e) {
        cout << "捕获到异常: " << e.what() << endl;
    }
    
    cout << "test02 end ... " << endl;
}

void test03() {
    string str1 = "hello";
    str1 += " world!";
    cout << str1 << endl;

    string str2 = "hello-";
    string str3 = "world";
    str2.append(str3, 1, 2);    // 字符串追加
    cout << str2 << endl;

    cout << "test03 end ..." << endl;
}

void test04() {
    string str1 = "http://www.word.888.word.com.word";
    cout << str1 << endl;
    while (1) {
        int ret = str1.find("word"); // 字符串查找, 返回查找字符串的位置
        cout << ret << endl;
        if ( ret < 0) {
            break;
        }
        str1.replace(ret, 4, "***");    // 字符串替换.
    }
    cout << str1 << endl;
    cout << "test04() end ..." << endl;
}

void test05() {
    string s = "This Is An Example";
    cout << "1) " << s << '\n';

    s.erase(7, 3); // 使用重载 (1) 擦除 " An"
    cout << "2) " << s << '\n';

    s.erase(s.find(' ')); // 使用重载 (1) 截掉从 ' ' 到字符串结尾的部分
    cout << "4) " << s << '\n';
    cout << "test05() end ..." << endl;
}

void test06() {
    // char *转为 string (默认支持)
    string str1;
    str1 = (string)"hello";
    cout << str1 <<endl;

    // string 不能直接转为char *, 需要使用成员函数 c_str()
    string str2 = "hello";
    char *p = (char *)str2.c_str();
    cout << p <<endl;
    cout << "test06() end ..." << endl;
}


int main() {
    test01();
    test02();
    test03();
    test04();
    test05();
    test06();
    return 0;
}




上一篇 下一篇

猜你喜欢

热点阅读