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