以下字串若為 string 則以 .c_str() 轉換。

使用 strtok 分割:
#include <iostream> #include <string.h> #include <stdlib.h> using namespace std; int main() { char s[101]="hello 12 num";//100 個字元為限 char *p; int x; p = strtok(s , " "); do{ cout << p << endl;//p 為數字字串 p = strtok(NULL," "); }while(p!=NULL); return 0; } 使用迴圈抓空白 #include <iostream> using namespace std; int main() { string s="12 3 974 38"; char *p; int a,i; for(i=a=0; i < s.length(); i++){ if(s[i]==' '){//找到空白 cout << s.substr(a,i-a) << endl; a=i+1; } } cout << s.substr(a,s.length()-a) << endl; return 0; }