這是一個奇怪的問題。這個功能可以更安全嗎?尋找提示和你的想法!
我寫了一個C函數。它的'像'strchr/strrchr。它應該在c字符串中尋找一個字符,但是要倒退,並返回一個指向它的指針。由於c字符串不是「空啓動的」,它還需要第三個參數「count」,表示它應該向後看的字符數。
/*
*s: Position from where to start looking for the desired character.
*c: Character to look for.
*count: Amount of tests to be done
*
* Returns NULL if c is not in (s-count,s)
* Returns a pointer to the occurrence of c in s.
*/
char* b_strchr(const char* s,int c,size_t count){
while (count-->0){
if (*s==c) return s;
s--;
}
return NULL;
}
我已經做它的一些測試,但 你看到它的任何缺陷?安全問題還是如此?任何增強功能?可以改進嗎? 更重要的是:這是一個壞主意嗎?
一些用法。
char* string = "1234567890";
printf("c: %c\n",*b_strchr(string+9,'5',10));//prints 5
printf("c: %c\n",*b_strchr(string+6,'1',7));//prints 1
編輯:新界面,一些變化。
/*
* from: Pointer to character where to start going back.
* begin: Pointer to characther where search will end.
*
* Returns NULL if c is not between [begin,from]
* Otherwise, returns pointer to c.
*/
char* b_strchr(const char* begin,int c,const char* from){
while (begin<=from){
if (*from==c) return from;
from--;
}
return NULL;
}
謝謝!沒有想過這件事。 – Tom 2009-07-03 02:48:59