實現C語言字符串操作的庫函數

#include <stdio.h>

//求字符串串長(版本一)
//用字符數組實現
int mystrlen1(char s[])
{
	int len = 0;
	while(s[len] != '\0')
	{
		len++;
	}
	
	return len;
} 

//求字符串串長(版本二)
//用字符指針實現 
int mystrlen2(char *s)
{
	int len = 0;
	
	while (*s != '\0')
	{
		len++;
		s++;
	}
	
	return len;
}

int main()
{
	char str[] = "hello";
	int n = mystrlen1(str);
	printf("%d\n",n);
	
	int m = mystrlen2(str);
	printf("%d\n",m);
	return 0;
}
#include <stdio.h >

//字符串拷貝(版本一)
//用數組實現 
void mystrcpy1(char s[],char t[])
{
	int i=0;
	while((s[i]=t[i]) != '\0') //先賦值,再比較是否爲串結束符
	{
		i++;
	}
} 

//字符串拷貝(版本二)
//用指針實現
void mystrcpy2(char *s,char *t)
{
	while((*s = *t) != '\0')
	{
		s++;
		t++;
	}
}

//字符串拷貝(版本三)
//用指針實現
void mystrcpy(char *s, char *t)
{
	while (*s++ = *t++);   //C中非0即表示邏輯真,所以不用和’\0’比較了
			
}
 
int main()
{
	char a[] ="hello";
	char b[100],c[100];
	mystrcpy1(b,a);
	printf("%s\n",b);
	
	mystrcpy2(c,a);
	printf("%s\n",c);
	return 0;
}

#include <stdio.h>

//字符串比較版本一
//用數組實現 
int mystrcmp1(char s[],char t[])
{
	int i;
	for(i=0;s[i]==t[i];i++)
	{
		if(s[i]=='\0')
		{
			return 0;
		}
	}
	return s[i]-t[i];
}

//字符串比較版本二
//用字符指針實現
int mystrcmp2(char *s,char *t)
{
	while(*s == *t)
	{
		if(*s == *t)
		{
			return 0;
		}
		s++;
		t++;
	}
	return *s-*t;
} 
int main()
{
	char s1[] = "hello",s2[] = "Java";
	printf("%d\n",mystrcmp1(s1,s2)>0?1:-1);
	printf("%d\n",mystrcmp2(s1,s2)>0?1:-1);
	return 0;
} 


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