C++入门:string常用操作指南
前言C语言中字符串是以\0结尾的一些字符集合为了操作方便C标准库中提供了一些str系列的库函数但是这些库函数与字符串是分离开的不太符合OOP思想而C中提供了string类string相对来说会更安全、更方便并且功能更加完善。本篇文章整理了string类的常用用法便于初学者参考和查阅。1.引入头文件使用string类时需包含的头文件#includeiostream #includestring如果项目小或者不想每次在开头加std::可以#includeiostream #includestring using namespace std;2.创建和初始化string s1; //空字符串 string s2 hello; //普通初始化 string s3(world); //构造函数 string s4(5, a); //aaaaa string s5 s2; //拷贝构造 string s6 s2 s3; //拼接hello world3.长度、容量和访问string s hello; cout s.size() endl; //长度5 cout s.length() endl; //也是返回长度 cout s.empty() endl; //判断是否为空 cout s[0] endl; //h不检查越界 cout s.at(1) endl; //e越界抛异常 cout s.front() endl; //第一个字符 cout s.back() endl; //最后一个字符 s[0] H; //修改4.修改字符串string s hello; s world; //追加 s.append(!); //追加 s.push_back(?); //追加一个字符 s.insert(0, say: ); //在0位置插入 s.erase(0, 5); //从0位置删除5个字符 s.replace(0, 5, Hi); //替换 s.clear(); //清空5.查找和子串string s hello world size_t pos s.find(world) if(pos ! string::nops) { cout pos endl } else { cout find fail endl } string sub s.substr(0, 5) // 从下标0开始取5个字符注find没找到时返回nops总结string类是C中最常用的字符串类型此文章中所涉及的几类操作是最常用的操作掌握后可以覆盖很多字符串的使用场景。