strtok(), strtok_s() 字符串分割函数
strtok(), strtok_s() 字符串分割函數(shù)
?//strtok()函數(shù)原型/*_Check_return_ _CRT_INSECURE_DEPRECATE(strtok_s) _CRTIMP char *? __cdecl strtok(_Inout_opt_z_ char * _Str, _In_z_ const char * _Delim);*/
當strtok()在參數(shù)_Str的字符串中發(fā)現(xiàn)參數(shù)_Delim中包涵的分割字符時,則會將該字符改為\0 字符。
在第一次調(diào)用時,strtok()必需給予參數(shù)_Str字符串,往后的調(diào)用則將參數(shù)_Str設(shè)置成NULL。每次調(diào)用成功則返回指向被分割出片段的指針。
需要注意的是,使用該函數(shù)進行字符串分割時,會破壞被分解字符串的完整,調(diào)用前和調(diào)用后的s已經(jīng)不一樣了。
第一次分割之后,原字符串str是分割完成之后的第一個字符串,剩余的字符串存儲在一個靜態(tài)變量中。
//將字符串"ab,cde,fghi"按照","分割。 char str[] = "ab,cde,fghi"; char *p[4]; p[0]= strtok(str, ","); int i = 0; while (p[i] != NULL) {i++;p[i]= strtok(NULL, ","); } p[i] = "\0"; for (int i = 0; i < 4; i++) {cout << p[i] << endl; }?
?
//strtok_s()函數(shù)原型 /*_Check_return_ _CRTIMP_ALTERNATIVE char * __cdecl strtok_s(_Inout_opt_z_ char * _Str, _In_z_ const char * _Delim, _Inout_ _Deref_prepost_opt_z_ char ** _Context);*/仍然會破壞原字符串的完整性。但是函數(shù)將剩余的字符串存儲在_Context變量中,而不是靜態(tài)變量中,從而保證了安全性。
char ** _Context參數(shù)是一個指向char *的指針變量,用來在strtok_s內(nèi)部保存切分時的上下文,以應(yīng)對連續(xù)調(diào)用分解相同源字符串。?
strtok函數(shù)在提取字符串時使用了靜態(tài)緩沖區(qū),因此,線程不安全。如果要顧及到線程的安全性,應(yīng)該使用strtok_s。
strtok_s實際上就是將strtok內(nèi)部隱式保存的this指針,以參數(shù)的形式與函數(shù)外部進行交互。由調(diào)用者進行傳遞、保存甚至是修改。
需要調(diào)用者在連續(xù)切分相同源字符串時,除了將str參數(shù)賦值為NULL,還要傳遞上次切分時保存下的_Context。
//將字符串"hello world,my name is congcong."按照","分割。 char str[] = "hello world,my name is congcong."; char *p[3]; char *buf; p[0]=strtok_s(str, ",",&buf); int i = 0; while (p[i]) {i++;p[i] = strtok_s(NULL, ",", &buf); } p[i] = "\0"; for (int i = 0; i < 3; i++) {cout << p[i] << endl; }?連續(xù)調(diào)用分解相同源字符串時,strtok_s()函數(shù)更加直觀的體現(xiàn)了其便捷性。
//將字符串"hello world,my name is congcong."按照","和" "分割。 //先按","分割,在每個字串里面按照" "分割。雙重循環(huán)過程中,需記錄出剩下的串。 char str[] = "hello world,my name is congcong."; char *p[8]; char *buf; char *buftmp; char *strtmp = new char[strlen(str)+1]; strcpy(strtmp, str); //p[0] = strtok_s(strtmp, ",", &buf); int i = 0; while (p[i] = strtok_s(strtmp, ",", &buf)) {strtmp = p[i];//p[i] = strtok_s(strtmp, " ", &buftmp);while (p[i] = strtok_s(strtmp, " ", &buftmp)){i++;//p[i] = strtok_s(NULL, " ", &buftmp);strtmp = NULL;}//p[i] = strtok_s(NULL, ",", &buf);strtmp = NULL; } //p[i] = "\0"; for (int j = 0; j < i; j++) {cout << p[j] << endl; }總結(jié)
以上是生活随笔為你收集整理的strtok(), strtok_s() 字符串分割函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2021-02-25
- 下一篇: c++ 如何给 “运行中“ 的线程传递数