zoukankan      html  css  js  c++  java
  • 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;
    	
    }
    


     

  • 相关阅读:
    高级特性(7)- 高级AWT
    洛谷 P1948 [USACO08JAN]电话线Telephone Lines
    洛谷 P2015 二叉苹果树
    洛谷 P2014 选课
    洛谷 P1560 [USACO5.2]蜗牛的旅行Snail Trails(不明原因的scanf错误)
    cogs 10. 信号无错传输
    cogs 9. 中心台站建设。。。
    洛谷 P1731 生日蛋糕
    洛谷 P1092 虫食算
    洛谷 P1034 矩形覆盖
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5205517.html
Copyright © 2011-2022 走看看