主要涉及到string類的兩個函數find和substr:
find()函數的用法:
原型:size_t find ( const string& str, size_t pos = 0 ) const;
功能:查找子字符串第一次出現的位置。
參數說明:str為子字符串,pos為初始查找位置。
返回值:找到的話返回第一次出現的位置,否則返回string::npos
//find函數返回類型 size_type string s("1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i"); string flag; string::size_type position; //find 函數 返回jk 在s 中的下標位置 position = s.find("jk"); if (position != s.npos) //如果沒找到,返回一個特別的標志c++中用npos表示,我這里npos取值是4294967295, { cout << "position is : " << position << endl; } else { cout << "Not found the flag" + flag; } //find 函數 返回flag 中任意字符 在s 中第一次出現的下標位置 flag = "c"; position = s.find_first_of(flag); cout << "s.find_first_of(flag) is : " << position << endl; //從字符串s 下標5開始,查找字符串b ,返回b 在s 中的下標 position=s.find("b",5); cout<<"s.find(b,5) is : "<<position<<endl; //查找s 中flag 出現的所有位置。 flag="a"; position=0; int i=1; while((position=s.find_first_of(flag,position))!=string::npos) { //position=s.find_first_of(flag,position); cout<<"position "<<i<<" : "<<position<<endl; position++; i++; } //查找flag 中與s 第一個不匹配的位置 flag="acb12389efgxyz789"; position=flag.find_first_not_of (s); cout<<"flag.find_first_not_of (s) :"<<position<<endl; //反向查找,flag 在s 中最后出現的位置 flag="3"; position=s.rfind (flag); cout<<"s.rfind (flag) :"<<position<<endl; }
substr()函數用法:
功能:獲得子字符串
返回值:子字符串
string a=s.substr(0,5); 從第0位開始的長度為5的字符串.默認時的長度為從開始位置到尾
string字符串分割,並把子字符串放入數組:
#include <iostream> #include <vector> #include <string.h> using namespace std; vector<string> fenge1(string a,char c) { vector<string> b; int pos=0,i,len=a.length(); for(i=0;i<len;i++) { if(i==0&&a[i]==c) pos=i+1; else if(a[i]==c) { b.push_back(a.substr(pos,i-pos)); pos=i+1; } else if(i==len-1) { b.push_back(a.substr(pos,i-pos+1)); } } return b; } vector<string> fenge2(string a,char c) { a=a+c; int i,len=a.length(),pos; vector<string> b; for(i=0;i<len;i++) { pos=a.find(c,i); if(pos<len) { b.push_back(a.substr(i,pos-i)); i=pos; } } return b; } int main() { string s="12,11,4"; vector<string> a=fenge2(s,','); for(auto i:a) cout<<i<<' '; }
string字符串分割,並把數字子字符串轉成int型,放入數組:
用到從c_str(),atoi()函數,字符串轉換成int型 int k=atoi(str.substr(i,pos-i).c_str());
#include <iostream> #include <stdlib.h> #include <string> #include <vector> using namespace std; typedef string::size_type sz; int main() { string str="11,12,13,14"; string p=","; str=str+p; vector<int> a; sz i,pos,len=str.size(); for(i=0;i<len;i++) { pos=str.find(p,i); if(pos<len) { int k=atoi(str.substr(i,pos-i).c_str()); a.push_back(k); i=pos; } } for(int j:a) cout<<j<<endl; return 0; }