C++中搜索、截取字符串

演示样例中有具体凝视,直接上代码:

#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
int main(void){
	string str1="hi,test,hello";
	string str2="test";
	//搜索子串。返回子串第一个字符的索引
	cout << str1.find(str2)<<endl;
	//假设不存在,返回内置常量string::npos,在一些编译器中通常为4294967295
	cout << str1.find('k')<<endl;
	//从指定索引開始搜索
	cout <<str1.find('h',2)<<endl;
	//从指定索引搜索指定字符串的前n个字符
	cout <<str1.find("her",1,2)<<endl;
	
	//在指定字符集合中搜索字符,返回其索引
	cout <<str1.find_first_of("AaEeIiOoUu")<<endl;
         //从指定索引处開始在指定字符集合中搜索字符
	cout <<str1.find_first_of("AaEeIiOoUu",2)<<endl;
         //从指定索引处開始在指定字符集合中搜索指定长度字符
	cout <<str1.find_first_of("AaEeIiOoUu",2,2)<<endl;
	
	//在指定字符集合中逆向搜索字符,返回字符最后索引,相同也具有上面另外两个重载方法
	cout <<str1.find_last_of("AaEeIiOoUu")<<endl;
	
	//查找字符串中第一个不在字符集合中的字符
	cout <<str1.find_first_not_of("AaEeIiOoUu")<<endl;
	//查找字符串中最后一个不在字符集合中的字符
	cout <<str1.find_last_not_of("AaEeIiOoUu")<<endl;
	
	//逆向搜索,也具有和find()一样的重载方法
	cout <<str1.rfind('l')<<endl;
	
	//截取子串
	string str3=str1.substr(3,4);
	cout <<str3<<endl;
	return 0;
	
}


 

posted @ 2016-02-21 20:40  mengfanrong  阅读(9870)  评论(0编辑  收藏  举报