【一個按標誌分拆字串的好方法】strtok函數簡介及應用。

來源:互聯網
上載者:User

剛剛接觸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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.