C++字符串(string)操作解析:从基础到进阶

1. 字符串基础:大小与容量

cpp

void test1() {
    string s1("Hello World");
    cout << "size : " << s1.size() << endl; // 输出字符串长度
    cout << "capacity = " << s1.capacity() << endl; // 输出字符串容量
    
    s1.reserve(100); // 预留空间
    cout << "reserve capacity = " << s1.capacity() << endl;
    
    s1.clear(); // 清除字符串内容
    cout << "clear size : " << s1.size() << endl;
    cout << "clear capacity = " << s1.capacity() << endl;
    cout << "clear s1 : " << s1 << endl;
}
  • size(): 返回字符串实际长度

  • capacity(): 返回字符串当前分配的存储空间大小

  • reserve(n): 预留空间,避免频繁重新分配内存

  • clear(): 清空字符串内容,但通常不会改变容量

2. 字符串遍历与访问

cpp

void test2() {
    string s1("Hello World");
    
    // 使用下标访问
    for (int i = 0; i < s1.size(); i++) {
        cout << s1[i] << " ";
    }
    
    // 使用迭代器
    string::iterator it = s1.begin();
    while (it != s1.end()) {
        cout << *(it++) << " ";
    }
    
    // 使用反向迭代器
    string::reverse_iterator rit = s1.rbegin();
    while (rit != s1.rend()) {
        cout << *(rit++) << " ";
    }
    
    // 使用范围for循环
    for (auto s : s1) {
        cout << s << " ";
    }
}

C++提供了多种遍历字符串的方式:

  1. 下标操作符[]

  2. 正向迭代器iterator

  3. 反向迭代器reverse_iterator

  4. 范围for循环(C++11引入)

3. 字符串修改操作

增加内容

cpp

// push_back: 尾部增加一个字符
s2.push_back('Y');

// append: 在末尾添加字符串
s3.append("YM");
s3.append(5, 'y'); // 添加5个'y'

// insert: 在指定位置插入
s4.insert(5, " YM");
s4.insert(5, 3, '*'); // 插入3个'*'

// += 运算符
s5 += " YM";

删除内容

cpp

// pop_back(): 删除最后一个字符
s6.pop_back();

// erase: 删除指定位置字符
s7.erase(8, 1); // 删除下标8开始的1个字符
s7.erase(s7.begin()); // 删除开头字符

修改内容

cpp

// replace: 替换内容
s8.replace(6, 2, "YM"); // 将下标6开始的2个字符替换为"YM"

// swap: 交换内容
swap(s9, s10); // 算法库的swap
s9.swap(s10);  // 字符串类的swap,效率更高

4. 字符串查找与子串操作

cpp

void test4() {
    string s1("Hello World");
    
    // find: 正向查找
    size_t pos = s1.find('l');
    
    // rfind: 反向查找
    size_t rpos = s1.rfind('l');
    
    // 查找第一个出现在/不出现在给定集合中的字符
    size_t fpos = s1.find_first_of("ol");
    size_t nfpos = s1.find_first_not_of("ol");
    
    // substr: 获取子串
    string s = s1.substr(pos); // 从pos到结尾
    string s_part = s1.substr(pos, 3); // 从pos开始3个字符
}

查找函数返回string::npos(通常是size_t的最大值)表示未找到。

5. 字符串比较

字符串比较可以直接使用关系运算符:

cpp

string a = "apple";
string b = "banana";

if (a < b) { // 字典序比较
    cout << "a comes before b";
}

// 或者使用compare函数
int result = a.compare(b);
if (result < 0) {
    cout << "a is less than b";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值