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;
    
}


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