程序设计实习(7) —— string 类

string 类是模板类:

1
typedef basic_string<char> string

成员函数

  • 构造函数:

    1
    2
    3
    4
    5
    6
    
    string s1("Hello");
    string month = "March";
    string s2(8,'x')
    string error1 = 'c'; // 错
    string error2('u'); // 错
    string error4(8); // 错
    

    支持流插入/提取运算符, 支持 getline 函数.

  • 访问字符:

    1
    2
    
    s1[0] = 'h';
    s1.at(0) = 'h';
    

    at 函数会检查下标是否越界, 如果越界会抛出异常.

  • 复制:

    1
    2
    
    string s3 = s1; // 复制
    s3.assign(s1); // 复制
    
  • 比较: 用 ==, !=, <, <=, >, >= 运算符.

  • 查找:

    1
    2
    3
    
    s1.find('l'); // 返回第一个 'l' 的下标
    s1.find('l', 3); // 从下标 3 开始查找
    s1.rfind('l'); // 返回最后一个 'l' 的下标
    

    如果没有找到, 返回 string::npos (即 -1).

  • 拼接:

    1
    2
    
    s1 += " world"; // 拼接
    s1.append(" world"); // 拼接
    
  • 删除:

    1
    
    s1.erase(0, 2); // 删除下标 0 到 2 的字符
    
  • 替换:

    1
    
    s1.replace(2, 3, "haha") // 从下标 2 开始的 3 个字符替换为 "haha"
    
  • 插入:

    1
    
    s1.inqsert(2, "abc"); // 在下标 2 处插入 "abc"
    
  • 子串:

    1
    
    s1.substr(2, 3); // 从下标 2 开始的 3 个字符
    
  • 流处理: 类似 istreamosteram 进行标准流输入输出, 我们用 istringstreamostringstream 进行字符串上的输入输出, 也称为内存输入输出.

    1
    2
    3
    4
    5
    
    string input = "12 Hello";
    istringstream iss(input);
    int a;
    string s;
    iss >> a >> s; // 读取整数和字符串
    
本文遵循 CC BY-NC-SA 4.0 协议
使用 Hugo 构建