實現字符串函數(下)

衆所周知,下冊比上冊難

我們今天要實現的函數是:
Strcmp();字符串比較函數
Memcpy();複製函數
memmove();可重疊複製函數

int Strcmp(const char* a, const char* b){
	assert(a != NULL && b != NULL);
	if (*a == '\0'&& *b == '\0'){ return 0; }
	if (*a == '\0'&& *b != '\0'){ return -1; }
	if (*a != '\0'&&*b == '\0'){ return 1; }
	while (*a != '\0' && *b != '\0'){
		if (*a > *b){
		
			return 1;
		
		}
		else if (*a < *b){
			return -1;

		}
		else { ++a; ++b; }

	}
	return 0;
}

``

    void *Memcpy(void *destin,const  void *source, unsigned n){
    	assert(destin != NULL && source != NULL);
    
    	char* p1 = (char*)destin;
    	char* p2 = (char*)source;
    	while (n--){
    	
    		*p1 = *p2;
    		++p1;
    		++p2;
    	
    	
    	}
    	//printf("%s\n", destin);   測試代碼,原數組爲數字也可;
    	return destin;

}

``


    void *Memmove(void * dest, const void *src, int count)
    {
    
    	assert(dest != NULL && src != NULL);
    	char* p1 = (char*)dest;
    	char* p2 = (char*)src;
    
    	if (dest > src){
    		while (count--){
    		
    			*(p1 + count) = *(p2 + count);
    		
    		}
    		printf("1\n");
    	}
    	else {
    		while (count--){
    			*p1 = *p2;
    			p1++;
    			p2++;
    
    		}
    	}
    	return dest;
    }

``
需要注意的是:最後兩個函數裏面的數字爲,你要複製的字節空間大小!!!

切記,切記,切記。

因爲本來你的指針並沒有大小,我們強制轉化爲了char*,這每加+便是1字節,所以你的數字必須是空間大小

舉例:

int a[4]={1,2,3,4};
memmove(a,a+1,8);

輸出結果2,3,3,4
後面那個8表示2個int即兩位數。
再比如:

char a[]="test";
memmove(a,a+1,2);

輸出結果:esst
這裏因爲字符串的單字符大小爲1字節,所以輸出這樣。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章