拆分字串 代碼

來源:互聯網
上載者:User

 

// crt_strtok.c// compile with: /W3// In this program, a loop uses strtok// to print all the tokens (separated by commas// or blanks) in the string named "string".//#include <string.h>#include <stdio.h>char string[] = "A string\tof ,,tokens\nand some  more tokens";char seps[]   = " ,\t\n";char *token;int main( void ){   printf( "Tokens:\n" );    // Establish string and get the first token:   token = strtok( string, seps ); // C4996   // Note: strtok is deprecated; consider using strtok_s instead   while( token != NULL )   {      // While there are tokens in "string"      printf( " %s\n", token );      // Get next token:       token = strtok( NULL, seps ); // C4996   }} Astringoftokensandsomemoretokensstrtok原型  char *strtok(char *s, const char *delim);功能  分解字串為一組字串。s為要分解的字串,delim為分隔字元字串。說明  首次調用時,s指向要分解的字串,之後再次調用要把s設成NULL。   strtok在s中尋找包含在delim中的字元並用NULL('')來替換,直到找遍整個字串。   char * p = strtok(s,";");   p = strtok(null,";");   在調用的過程中,字串s被改變了,這點是要注意的。傳回值    從s開頭開始的一個個被分割的串。當沒有被分割的串時則返回NULL。       所有delim中包含的字元都會被濾掉,並將被濾掉的地方設為一處分割的節點。strtok函數在C和C++語言中的使用  strtok函數會破壞被分解字串的完整,調用前和調用後的s已經不一樣了。如果   要保持原字串的完整,可以使用strchr和sscanf的組合等。c#include <string.h>   #include <stdio.h>   int main(void)   {   char input[16] = "abc,d";   char *p;   /**/ /* strtok places a NULL terminator   in front of the token, if found */   p = strtok(input, ",");   if (p) printf("%s\n", p);   /**/ /* A second call to strtok using a NULL   as the first parameter returns a pointer   to the character following the token */   p = strtok(NULL, ",");   if (p) printf("%s\n", p);   return 0;   }c++#include <iostream>   #include <cstring>   using namespace std;   int main()   {   char sentence[]="This is a sentence with 7 tokens";   cout<<"The string to be tokenized is:\n"<<sentence<<"\n\nThe tokens are:\n\n";   char *tokenPtr=strtok(sentence," ");   while(tokenPtr!=NULL)   {   cout<<tokenPtr<<'\n';   tokenPtr=strtok(NULL," ");   }   cout<<"After strtok, sentence = "<<sentence<<endl;   return 0;   }   函數第一次調用需設定兩個參數。第一次分割的結果,返回串中第一個 ',' 之前的字串,也就是上面的程式第一次輸出abc。   第二次調用該函數strtok(NULL,","),第一個參數設定為NULL。結果返回分割依據後面的字串,即第二次輸出d。   strtok是一個線程不安全的函數,因為它使用了靜態分配的空間來儲存被分割的字串位置   安全執行緒的函數叫strtok_r,ca   運用strtok來判斷ip或者mac的時候務必要先用其他的方法判斷'.'或':'的個數,因為用strtok截斷的話,比如:"192..168.0...8..."這個字串,strtok只會截取四次,中間的...無論多少都會被當作一個key

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.