赞
踩
1.用法描述:
2.函数原型:
3.补充:
- #include<iostream>
- #include<string>
- using namespace std;
-
- void search_factor()
- {
- int pos;//pos的全称为position,即位置的意思。
-
- //1.查找字符串“wo”在字符串"hello world!hello world!"中第一次出现的位置
- string s1="hello world!hello world!";
- pos=s1.find("wo") ;
- if(pos==-1)
- cout<<"查找失败!"<<endl;
- else
- cout<<"找到字符位置,其位置pos = "<<pos<<endl;
-
- //2. 查找字符串“wo”在字符串"hello world!hello world!"中最后一次出现的位置
- pos=s1.rfind("wo");
- cout<<"找到字符位置,其位置pos = "<<pos<<endl;
-
- //3.查找字符串hello在字符串dasudgfhshelldasdhello中第一次出现的位置
- string s2="dasudgfhshelldasdhello";
- string s3="hello";
- pos=s2.find(s3,0);
- cout<<"字符串hello在字符串dasudgfhshelldasdhello中第一次出现的位置为:"<<pos<<endl;
-
- //4.从前往后查,查找字符串"hello"中首个与字符串"dasudgfhshelldasdhello"重复的字符位置
- //具体起来就是先查h是否存在于母串中,如果没有就查e是否在母串中 ,依次往下查,查到即返回下标
- pos=s2.find_first_of(s3);
- cout<<"从前往后查,字符串hello中首个与字符串dasudgfhshelldasdhello重复的字符位置是:"<<pos<<endl;
-
- //5.从后往前查,查找字符串"hello"中首个与字符串"dasudgfhshelldasdhello"重复的字符位置
- pos=s2.find_last_of(s3) ;
- cout<<"从后往前查,字符串hello中首个与字符串dasudgfhshelldasdhello重复的字符位置是:"<<pos<<endl;
-
- //6.查找字符串"hello"中首个与字符串"hhhhehhllloo"不重复的字符位置
- string str="hhhhewhhllloo";
- pos=str.find_first_not_of(s3);
- cout<<"查找字符串hello中首个与字符串hhhhehhllloo不重复的字符位置: "<<pos<<endl; //返回e的下标
-
- //7.查找字符串"hello"在字符串"hhhhehellohlllohelloo"中出现的所有位置
- string ss="hhhhehellohlllohelloo";
- string s="hello";
- pos=0;
- int i=1;
- cout<<"查找字符串hello在字符串hhhhehellohlllohelloo中出现的所有位置: "<<endl;
- while((pos=ss.find(s,pos))!=string::npos)
- {
- cout<<"第"<<i<<"个位置: "<<pos<<endl;
- pos++;
- i++;
- }
-
- }
- void replace_factor()
- {
- string s2="hello world!hello world!";
- s2.replace(1,3,"aaaa"); //从下标1开始去除3个字符 ,在下标位置1处插入新字符串
- cout<<"s2 = "<<s2<<endl;
- }
- int main()
- {
- search_factor();
- replace_factor();
- return 0;
- }
-
- /*
- 打印结果:
- 找到字符位置,其位置pos = 6
- 找到字符位置,其位置pos = 19
- 字符串hello在字符串dasudgfhshelldasdhello中第一次出现的位置为:17
- 从前往后查,字符串hello中首个与字符串dasudgfhshelldasdhello重复的字符位置是:7
- 从后往前查,字符串hello中首个与字符串dasudgfhshelldasdhello重复的字符位置是:21
- 查找字符串hello中首个与字符串hhhhehhllloo不重复的字符位置: 5
- 查找字符串hello在字符串hhhhehellohlllohelloo中出现的所有位置:
- 第1个位置: 5
- 第2个位置: 15
- s2 = haaaao world!hello world!
- */

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。