剛剛接觸strtok函數,感覺十分神奇。
定義:
strtok
文法:
#include <string.h> char *strtok( char *str1, const char *str2 ); |
功能:函數返回字串str1中緊接“標記”的部分的指標, 字串str2是作為標記的分隔字元。如果分隔標記沒有找到,函數返回NULL。為了將字串轉換成標記,第一次調用str1 指向作為標記的分隔字元。之後所以的調用str1 都應為NULL。
例如:
char str[] = "now # is the time for all # good men to come to the # aid of their country"; char delims[] = "#"; char *result = NULL; result = strtok( str, delims ); while( result != NULL ) { printf( "result is \"%s\"\n", result ); result = strtok( NULL, delims ); }這個範例的結果為:
result is "now "
result is " is the time for all "
result is " good men to come to the "
result is " aid of their country"
實現了通過'#'分拆的目的。
典型應用,如HDU 1106:點擊開啟題目連結
要求按5為分割進行拆解字串,並轉換為字串進行排序。一般的方法為直接類比,但是如果靈活使用字串分割函數strtok(注意它的傳回值是指標),字串轉數字函數atoi(),這個題十分簡單。
#include <iostream>#include <algorithm>#include <cstring>#include <string>#include <string.h>#include <stdlib.h>using namespace std;bool cmp(int a,int b){return a<b;}int num[1009];int main(){char tar[1009];while(cin>>tar){string numpack[1000];memset(num,0,sizeof(num));int pos=0;int start=0,end=0;char *temp;temp=strtok(tar,"5"); //按5分開也while(temp!=NULL) { numpack[pos]=temp; temp=strtok(NULL,"5"); //基本用法 ,把指標存入數組中 pos++; } for(int i=0;i<pos;i++){num[i]=atoi(numpack[i].c_str());}sort(num,num+pos,cmp);for(int i=0;i<pos;i++){cout<<num[i];if(i!=pos-1)cout<<" ";elsecout<<endl;}}return 0;}