1.string.find函数

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 
 6 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 7 
 8 int main(int argc, char** argv) {
 9     
10     string s;
11     string str;
12     char *p = "abc";
13     
14     int index;
15     
16     getline(cin,s);
17     cout<<"s="<<s<<endl;
18     
19     getline(cin,str);
20     cout<<"str="<<str<<endl;
21     
22     index = s.find(str);
23     cout<<"char index="<<index<<endl;
24     
25     index = s.find(p);
26     cout<<"string index="<<index<<endl;
27     
28     return 0;
29 }

 

2. 取子串

#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
using namespace std;

//输入2015-10-22 
int riqi(string str){
    int i = 0;
    int year;
    int month;
    int day;
    int i_start,i_end;
    string tmp;
    
    i_start = str.find("-");//第一个'-'
    tmp = str.substr(0,i_start);//取从0下标开始的i_start个字符
    year = atoi(tmp.c_str());//tmp.c_str()转化为C语言中字符串指针
    
    i_end = str.rfind("-");//最后一个'-'
    tmp = str.substr(i_start+1,i_end - i_start);
    month = atoi(tmp.c_str());

    tmp = str.substr(i_end+1);
    day = atoi(tmp.c_str());
    cout<<year<<" "<<month<<' '<<day<<endl;
    //输出的结果为  2015 10 22
    return 0;
}

 

posted on 2016-09-08 10:02  人生一世,草木一秋。  阅读(3357)  评论(0编辑  收藏  举报