一:strtok
C/C++:char *strtok(char s[], const char *delim);
s 代表須要切割的字符串,delim代表切割的標志,參數都為比選!返回指向切割部分的指針,假設沒有切割成功就返回NULL.
一個簡單的樣例:
void main() { char *str = "jscese test strtok"; char *delim = " "; char *pstr = NULL; pstr = strtok(str, delim); printf("the first str==%s \n", pstr); while ((pstr = strtok(NULL, delim)) != NULL) { printf("the next str==%s \n", pstr); } }
以上看出第一次之后 切割之后,假設還要繼續傳的參數就是 NULL。由於strtok是把切割的標志位置設置成了 /0
切割完之后的字符串: jscese/0test/0strtok
所以往后的開頭指針的位置都是/0處。所以傳NULL。
以上結果為:
the first str==jscese the next str==test the next str==strtok
由於它在處理切割一個字符串的時候,保存移動位置的指針變量是一個靜態變量。
這種話,在同一個字符串的處理中。假設有多個strtok的同一時候操作,就會指針錯亂了,得不到想到的切割結果。
相相應的有線程安全的strtok_r函數。
二:split
java:stringObj.split([separator,[limit]]);
stringObj 指須要切割的字符串實體.
separator 切割的標志.
limit 代表返回的元素個數,為可選參數。
返回一個字符串數組.
簡單樣例:
public void split() { String testString = "jscese.test.split"; String[] splitarray1 = testString.split("\\."); for (int i = 0; i < splitarray1.length; i++) { System.out.println(splitarray1[i]); } String[] splitarray2 = testString.split("\\.", 2); for (int i = 0; i < splitarray2.length; i++) { System.out.println(splitarray2[i]); } }
以上以 "."為切割符,可是為特殊字符須要轉義 全部在前面須要加 "\\"
java中 像 + * | \ .等都須要加轉義。
以上執行結果:
jscese
test
split
jscese
test.splilt
撰寫不易。轉載請注明出處:http://blog.csdn.net/jscese/article/details/26447589