如"A|B|C|D" 根據|分割,得到陣列["A","B","C","D"]
char *propertyArr[4] = { "-1","-1" ,"-1","-1" }; custom_string("A|B|C|D", "|", propertyArr, 4);
void custom_string(char *str, char *delimiter, char *arr[], int maxLength) { char *token = strtok(str, delimiter); int arrIndex = 0; while (token != NULL && arrIndex < maxLength) { TC_write_syslog("token : %s\n", token); arr[arrIndex++] = token; // 儲存分割後的子串 TC_write_syslog("test :%d, %s\n", arrIndex, token); token = strtok(NULL, delimiter); // 獲取下一個子串 } }
這裡要注意陣列長度的問題,需要事先給定陣列的長度。
如果你確定陣列的長度,則儘量將長度給得大一些。