訪客只能看到部份內容,免費 加入會員 或由臉書 Google 可以看到全部內容
#include <stdio.h> #include <string.h> int main () { char str[] ="- This, a sample string."; char * pch; printf ("Splitting string \"%s\" into tokens:\n",str); pch = strtok (str," ,.-"); while (pch != NULL) { printf ("%s\n",pch); pch = strtok (NULL, " ,.-"); } return 0; }
圖 1.
#include <iostream> #include <fstream> #include <string> #include <iomanip> #include <vector> using namespace std; typedef vector<string> vstring ; void split(vstring &szRet,string szStr,const char *del) { char *czStr = new char [szStr.size()+1]; //char szBuf[1024] = {'\0'} ; strcpy(czStr,szStr.c_str()); char *s = strtok(czStr,del); int cnt = 0 ; while( s != NULL ){ szRet.push_back(s) ; s = strtok(NULL, del); } delete [] czStr ; } int main(int argc, char* argv[]) { unsigned int i ; string inputFileName; string sample; string tran_sample; ifstream inputFile; if (argc>1){ inputFileName=string (argv[1]); } else{ cout << "輸入要開啟的檔名(包含副檔名):"; cin >> inputFileName; } inputFile.open (inputFileName.c_str(),ios::in); //檢查開啟的檔案是否正確 while(inputFile.fail()) { inputFile.clear(); cout << "查無此檔,請重新輸入:"; cin >> inputFileName; inputFile.open (inputFileName.c_str()); } //顯示輸入的檔案內容 string line ; long int lcount = 0 ; vstring word ; bool ret = false; while ( 1 ) { getline( inputFile , line ) ; if ( ! inputFile ) break ; ++lcount ; cout << setw(5) <<lcount << " : " << line << endl ; switch(lcount%3) { case 1: word.clear() ; split(word,line," "); for(i=0;i<word.size();i++){ cout<<word[i]<<endl; } break; case 2: break; case 0: cout <<"---------------\n"; break; } } inputFile.close(); return 0; }
vector<string> Split(char cHyphen, string InStr) { vector<string> vstrSplitData; string strtmp = ""; for ( unsigned int i = 0 ; i < InStr.Length() ; i++ ) { if ( InStr[i] != cHyphen ) { strtmp += InStr[i]; }else{ vstrSplitData.push_back(strtmp); strtmp = ""; } } if (strtmp != "") { vstrSplitData.push_back(strtmp); }; //最後一個區間 return vstrSplitData; }