strcat、strcpy、strcmp的實現,以及有關字符串處理需要注意的地方

註釋:以下所有測試在freescale codewarrior中完成
//將字符串t複製到字符串s
//sizeof(s) >= sizeof(t)
void strcpy(char* s, char*t)
{   
   while(*s++ = *t++);
}
我們在不同的字符串下測試函數的性能
1: char s[] ="hello"; //sizeof(s) == 6
    char t[] = "eleven";//sizeof(t) ==7
    測試結果: s = eleven,s的數組中沒有了'\0'字符,因爲s數組只有6個字節長
2: char s[LEN] = "hello"//LEN>=7則輸出符合我們預期

3:  char *s = "hello";
    cahr t[] = "eleven";
    測試結果是 s和t都沒有發生任何變化,why?因爲"hello"是放在靜態儲存區中的字符型常量,we just can't modify it...
    


//將字符串t連接到字符串s的末尾
//sizeof(s)必須能夠容納所有s和t中的有效字符包括結尾的'\0'
void strcat(char *s, char *t)
{
   
    while(*s) s++;

    while(*s++ = *t++);
    
}
如果當s的長度不足以包括所有的有效字符時,後面的數據將被切斷。

//比較字符串t和s的大小
int strcmp(char *s, char*t)
{
    while(*s == *t)
    {
       if(*s == '\0')
           return 0;
       s++;
       t++;
    }
    
    return *s- *t;
    
}


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