OJ中字串輸入及相關操作
1. 輸入資料方式
cin>>a>>b;
char a[10];
cin.getline(a,5);
char a,b,c;
cin.get(a);cin.get(b);cin.get(c);
輸入:
AB
CD
那麼a的值為'A',b的值為'B',c的值為'\n\
getline(istream &in, string &s)
在標頭檔案<iostream>中聲明瞭getline函式:
istream::getline
istream&getline (char* s, streamsize n );
istream&getline (char* s, streamsize n, char delim )
std::cin.getline (title,256);
C++中還定義了一個在std名字空間的全域性函式,因為這個getline函式的引數使用了string字串,所以宣告在了<string>標頭檔案中了。
istream&getline ( istream& is, string& str, char delim );
istream&getline ( istream& is, string& str );
std::getline (std::cin,name);
sort函式按從大到小排序,比較函式如下:
int comp(constint &a,const int &b)
{
returna>b;
}
Map使用find()函式確定是否包含相關key,如果返回值不等於map.end()就代表找到了。
2.字串逆序
stringstr("cvicses");
strings(str.rbegin(),str.rend());
cout <<s<<endl;
3.字串分割
標頭檔案:#include <string.h>
定義函式:char * strtok(char *s, const char *delim);
函式說明:strtok()用來將字串分割成一個個片段。引數s 指向欲分割的字串,引數delim 則為分割字串,當strtok()在引數s 的字串中發現到引數delim 的分割字元時則會將該字元改為\0 字元。在第一次呼叫時,strtok()必需給予引數s 字串,往後的呼叫則將引數s 設定成NULL。每次呼叫成功則返回下一個分割後的字串指標。
返回值:返回下一個分割後的字串指標,如果已無從分割則返回NULL。
#include<string.h>
main(){
char s[] = "ab-cd : ef;gh:i-jkl;mnop;qrs-tu: vwx-y;z";
char *delim = "-: ";
char *p;
printf("%s ", strtok(s, delim));
while((p = strtok(NULL, delim)))
{
printf("%s ", p);
printf("\n");
}
}
執行結果:
ab cd ef;gh i jkl;mnop;qrs tu vwx y;z //-與:字元已經被\0 字元取代
標頭檔案:#include <string.h>
strstr()函式用來檢索子串在字串中首次出現的位置,其原型為:
char*strstr( char *str, char * substr );
引數說明:str為要檢索的字串,substr為要檢索的子串。
返回值:返回字串str中第一次出現子串substr的地址;如果沒有檢索到子串,則返回NULL。
int main(int argc,char **argv)
{
char *haystack="aaa||a||bbb||c||ee||";
char *needle="||";
char* buf = strstr( haystack, needle);
while( buf != NULL )
{
buf[0]='\0';
printf("%s\n ", haystack);
haystack =buf + strlen(needle);
/* Get nexttoken: */
buf =strstr(haystack, needle);
}
return 0;
}
用STL進行字串的分割
涉及到string類的兩個函式find和substr:
1、find函式
原型:size_t find ( const string& str, size_t pos = 0 )const;
功能:查詢子字串第一次出現的位置。
引數說明:str為子字串,pos為初始查詢位置。
返回值:找到的話返回第一次出現的位置,否則返回string::npos
2、substr函式
原型:string substr ( size_t pos = 0, size_t n = npos )const;
功能:獲得子字串。
引數說明:pos為起始位置(預設為0),n為結束位置(預設為npos)
返回值:子字串
實現如下:
//字串分割函式
std::vector<std::string> split(std::stringstr,std::string pattern)
{
std::string::size_type pos;
std::vector<std::string> result;
str+=pattern;//擴充套件字串以方便操作
intsize=str.size();
for(int i=0;i<size; i++)
{
pos=str.find(pattern,i);
if(pos<size)
{
std::string s=str.substr(i,pos-i);
result.push_back(s);
i=pos+pattern.size()-1;
}
}
return result;
}