C++中string查找和取子串和整形轉化


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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM