第十八章 10string 型字符串的查找 简单

// 10string 型字符串的查找
/*#include <iostream>
using namespace std;
int main()
{
	char ch1[20];
	char *p, c='w';
	strcpy(ch1,"hellwo wordlxxdxxd");
	p = strchr(ch1,c); //在字符串中查找字符
	if(p){
		//这里的p-ch1, 相当于p在ch1中的位置
		//这里的p是指的从查找到字符后面的所有字符,
		//这里的位置有点不清楚样
		//还要提高
		//由于一个字符占一个字节,因此用p-ch1就是用求出p相对于ch1的偏移量,这个偏移量是相对于第一个字符而言,p最终指向的字符w,这样求出来的数值就是字符w在ch1中的位置
	   cout<<"字符的位置是:"<<p-ch1<<endl;
	}else{
	   cout<<"找到了"<<endl;
	}
    return 0;
}*/

//string 字符的查找
//利用string类的成员函数find可实现对字符串的查找功能,该函数会返回字符在字符串中第一次出现的位置,如果没有找到就返回string::npos;
//nops的string提供的一个常量,用来表示不存在的位置,许多平台npos的值都不一样,因此它的值由平台决定,一般是-1,不管什么平台,npos的值都不能作数组的下标,因此设置该常量,主要是为了解决移植的问题,另外用常量代替数值的方式也便于理解该数值的含义
/* 10 
#include <iostream>
#include <string>
using namespace std;
int main()
{
	string str="hello wordw";
	char ch='w';
	//int f = str.find(ch,0);
	//int f = str.find_first_not_of(ch,0); //查找第一个不与w相等的字符的位置
	//int f = str.find_first_of(ch,0); //查找w第一次出现的位置
	//这里不需要设置last_of的开始位置,因为他默认就是在字符串的最后位置查找
	//int f = str.find_last_of(ch,0); //查找2最后一次出现的位置
	//int f = str.find_last_of(ch); //查找2最后一次出现的位置

	int f = str.rfind(ch,9);

	if(f !=::string::npos){
	   cout<<ch<<"出现在"<<str<<"的第"<<f<<endl;
	}else{
	   cout<<"没有找到"<<endl;
	}
    return 0;
}*/

  

原文地址:https://www.cnblogs.com/xiangxiaodong/p/2698966.html