2 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超2個(gè)贊
仔細(xì)看看這兩段代碼就知道了:
關(guān)鍵,字符串后面都以 \0字符結(jié)束,而你的strlen函數(shù)是計(jì)算了\0字符的。
int _strncmp(char* a,char* b,int n)
{
int i=0,s;
while(a[i]==b[i] && a[i])
i++;
if(i>=n) //關(guān)鍵在這里,你的算法中,如果b比a短,也就是比較到了\0時(shí),i=0,返回了0,即相等
return 0;
else if(i<n && a[i]-b[i])
return 1;
else
return -1;
}
int _strncmp(char* a,char* b,int n)
{
int i=0,s;
while(!(s=a[i]-b[i]) && a[i] && i<=n) //他的算法中,你傳遞的n是包含\0字符的,因此當(dāng)b比a短的時(shí)候,必然會(huì)比較到 s=a[n]-b[n] ,s <> 0 ,因此返回的必然是非0,即不等,所以。。。
i++;
if(s<0)
return -1;
if(s>0)
return 1;
else
return 0;
}

TA貢獻(xiàn)1790條經(jīng)驗(yàn) 獲得超9個(gè)贊
void ltrim(char str[])
{
int count=0;//記錄字符串左邊有多少個(gè)空格
char *p=NULL;
p=str;
while(*p==' ' && *p!='\0')//循環(huán)檢查左邊空格的個(gè)數(shù)
{
count++;
p++;
}
p=str+count;
while(count>0 && *p!='\0')//循環(huán),把后面的字符前移
{
*(p-count)=*p;
p++;
}
*(p-count)='\0';
}
void rtrim(char str[])
{
int count=0;//記錄字符串右邊有多少個(gè)空格
char *p=NULL;
p=str;
while(*p!='\0')//循環(huán)找到字符串結(jié)束
{
p++;
}
p--;
while(p>=str && *p==' ')//循環(huán)消滅后面的空格
{
*p='\0';
p--;
}
}
void trim(char str[]) //直接調(diào)用上面兩個(gè)函數(shù)
{
ltrim(str);
rtrim(str);
}
void delchar(char str[],char ch)
{
int count=0;
char *p1=NULL,*p2=NULL,*Y=NULL;
p1=str;
while(*p1!='\0')
{
p1++;
count++;
}
Y=(char *)malloc(count+1);//為了節(jié)約運(yùn)算時(shí)間,申請一個(gè)緩沖內(nèi)存
//malloc函數(shù)要求引入#include<stdlib.h>函數(shù)
p1=str;
p2=Y;
while(*p1!='\0')
{
if(*p1!=ch)
{
*p2=*p1;
p2++;
}
p1++;
}
*p2='\0';
p1=str;
p2=Y;
while(*p2!='\0')
{
*p1=*p2;
p1++;
p2++;
}
*p1='\0';
free(Y);//釋放內(nèi)存
}
- 2 回答
- 0 關(guān)注
- 107 瀏覽
添加回答
舉報(bào)