练手代码。已测试。
包含 strlen, rev, strcat, strcmp, strstr, itoa
- #include <stdio.h>
- #include <assert.h>
- #define SWAP(a,b) (a)^=(b);(b)^=(a);(a)^=(b)
- int mystrlen(const char* src){
- assert( src!=NULL);
- char* ptr = src;
- while(*ptr){
- ptr++;
- }
- return ptr- src;
- }
- char * mystrcat(char* src, const char* dest){
- assert( src!=NULL && dest != NULL);
- char* ret = src;
- while(*src) src++;
- while(*src++ = *dest++);
- return ret;
- }
- char *myrev(char* str){
- assert(str!=NULL);
- char* ret, *start ;
- ret = start = str;
- while(*str) str++;
- str--;
-
- while(start<str){
- SWAP(*start, *str);
- start++,str--;
- }
- return ret;
- }
- int mystrcmp(const char* src, const char* dest){
- assert( src!=NULL && dest != NULL);
- while(*src && *dest && *src == *dest) src++, dest++;
- return *src - *dest;
- }
- char *myitoa(int num, char* buf){
- assert(buf!=NULL);
- char * ret = buf;
- int isNegtive = 0;
- if(num<0){
- num*=-1;
- isNegtive = 1;
- }
- do{
- *buf++ = num%10 + '0';
- }while(num/=10);
- // negtive
- if(isNegtive) *buf++ = '-';
- *buf = '\0';
- return myrev(ret);
- }
- char* mystrstr(const char* src, const char* dest){
- assert( src!=NULL && dest != NULL);
- if(!*dest) return src;
- while(*src){
- int i = 0;
- for(;*(src+i)==*(dest+i);i++){
- if(!*(dest+i+1))
- return src;
- }
- src++;
- }
- return NULL;
-
- }
- int main(){
- char test[10] = "abcd";
- printf("strlen: %d\n", mystrlen(test));
- printf("strcat %s\n", mystrcat(test,"xyz"));
- printf("myrev %s\n", myrev(test));
- printf("mystrcmp %d\n",mystrcmp("test",test));
- printf("mystrcmp %d\n",mystrcmp(test,"zyxdcba"));
- printf("mystrstr %s\n",mystrstr(test, "bc"));
- printf("myitoa %s \n", myitoa(-124, test));
- }
阅读(255) | 评论(0) | 转发(0) |