string函数的应用
字符串查找
find 方法 实例
string s ="Hello World,C++ is awesome!";//查找子串 size_t pos1 = s.find("World"); //pos1=6 size_t pos2 = s.find("Python"); //pos2=string::npos//查找字符 size_tpos3=s.find('c'); //pos3=13//从指定位置开始查找 size_tpos4=s.find('o',5); //pos4=7(从索引5开始找o)
字符串提取
substr 方法 实例
string s = "Hello World";string sub1= s.substr(6); //sub1=“WorLd"(从6到末尾) string sub2 = s.substr(6,3); //sub2="Wor" string sub3 = s.substr(0,5); //sub3="HeLLo"//错误示例 //string sub4=s.substr(2e);// 抛出异常(pos超出范围)
字符串替换
replace 实例
string s="Hello World";//替换子串 s.replace(6,5,"c++"); //s="HeLLo C++” s.replace(0,5,"Hi"); //S="Hi C++”//替换迭代器范围 s.replace(s.begin()+3,s.end(),"there!"); //s="Hithere!" //替换为c风格字符串 s.replace(3,5,"awesome"); // s="Hiawesome!"
对比表格
方法 | 核心功能 | 关键参数 | 返回值/副作用 | 常见用途 |
find | 查找子串或字符位置 | 子串/字符+起始置 | 索引或npos | 搜索、条件判断 |
substr | 提取子串 | 起始位置+长度 | 新字符串 | 分割、截取 |
replace | 替换指定区间内容 | 位置+长度 迭代器+新内容 | 修改原字符串 返回自身引用 | 动态修改字符串内容 |