C++ 字符串 8-- 18.22~24.string型字符串的查找

#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
     18-22 18.22~24.string型字符串的查找
---------------------------------*/
int main()
{
cout<<"-------C类 strchr()-----------:"<<endl;
char ch1[15];
char *p,c='w';
strcpy(ch1,"hello world");
cout<<ch1<<endl;
p =strchr(ch1,c); //在字符串ch1中查找字符变量c,并返回该字符在字符串中的地址
if(p)
{  cout<<"字符"<<c<<"的位置是"<<p-ch1<<endl;}//查找的目标字符的地址减去字符串的的首地址即为偏移量
else
cout<<"没有找到"<<endl;


cout<<"-------C++类 find()-----------:"<<endl;
string str1("hello world");
cout<<str1<<endl;
int f=str1.find('w',0);//从str1脚标0的位置开始查找字符‘w’第一次出现的位置
if(f!=string::npos)
{  cout<<"字符w第一次出现的位置是"<<f<<endl;}
else
cout<<"没有找到"<<endl;


cout<<"-------C++类 find_first_not_of()-----------:"<<endl;
str1="hello world";
cout<<str1<<endl;
f=str1.find_first_not_of('w',0);//从str1脚标0的位置开始查找非字符‘w’第一次出现的位置
if(f!=string::npos)
{  cout<<"非字符w第一次出现的位置是"<<f<<endl;}
else
cout<<"没有找到"<<endl;


cout<<"-------C++类 find_first_of()-----------:"<<endl;
str1="hello world";
cout<<str1<<endl;
f=str1.find_first_of('w',0);//从str1脚标0的位置开始查找字符‘w’第一次出现的位置
if(f!=string::npos)
{  cout<<"字符w第一次出现的位置是"<<f<<endl;}
else
cout<<"没有找到"<<endl;


cout<<"-------C++类 find_last_of()-----------:"<<endl;
str1="hello world w";
cout<<str1<<endl;
f=str1.find_last_of('w');//第二个参数删除,查找字符'w'最后一次出现的位置
if(f!=string::npos)
{  cout<<"字符w最后一次出现的位置是"<<f<<endl;}
else
cout<<"没有找到"<<endl;


cout<<"-------C++类 find_last_not_of()-----------:"<<endl;
str1="hello world w";
cout<<str1<<endl;
f=str1.find_last_not_of('w');//第二个参数删除,查找非字符'w'最后一次出现的位置
if(f!=string::npos)
{  cout<<"非字符w最后一次出现的位置是"<<f<<endl;}
else
cout<<"没有找到"<<endl;


cout<<"-------C++类 rfind()-----------:"<<endl;
str1="hello world w";
cout<<str1<<endl;
f=str1.rfind('w',10);//从第10位向前查找字符'w'第一次出现的位置
if(f!=string::npos)
{  cout<<"字符'w'从字符串脚标10的位置逆向查找,第一次出现的位置是"<<f<<endl;}
else
cout<<"没有找到"<<endl;


cout<<"-------C++类 rfind()-----------:"<<endl;
str1="hello world w";
cout<<str1<<endl;
f=str1.rfind('w');//去掉第二个参数,默认从最后一个字符向前查找字符'w'第一次出现的位置
if(f!=string::npos)
{  cout<<"字符'w'从字符串最末的位置逆向查找,第一次出现的位置是"<<f<<endl;}
else
cout<<"没有找到"<<endl;
return 0;

}

运行结果:

-------C类 strchr()-----------:
hello world
字符w的位置是6
-------C++类 find()-----------:
hello world
字符w第一次出现的位置是6
-------C++类 find_first_not_of()-----------:
hello world
非字符w第一次出现的位置是0
-------C++类 find_first_of()-----------:
hello world
字符w第一次出现的位置是6
-------C++类 find_last_of()-----------:
hello world w
字符w最后一次出现的位置是12
-------C++类 find_last_not_of()-----------:
hello world w
非字符w最后一次出现的位置是11
-------C++类 rfind()-----------:
hello world w
字符'w'从字符串脚标10的位置逆向查找,第一次出现的位置是6
-------C++类 rfind()-----------:
hello world w
字符'w'从字符串最末的位置逆向查找,第一次出现的位置是12
Press any key to continue

猜你喜欢

转载自blog.csdn.net/paulliam/article/details/80534300