#include<stdio.h>
#include<string.h>
int myStrcat(char c1[],char *c2){
int i=0;
char *t=c2;
while (c1[i]!='0') {
i++;
}
while(*t!='\0')
c1[i]=*t,i++,t++;
c1[i]='\0';
}
char c1[],char *c2
地址参数,能够共享空间;
*t=c2指向相同
字符串复制函数strcpy()
格式:strcpy(s1,s2)
功能:将字符串s2复制到字符数组s1中
说明
>s1是字符数组名或字符数组的开始地址,s2可以是数组名,也可以是一个字符串
>s1不能是字符串
>s1数组的长度应不小于s2的,以保证能够存储s2,否则会出现意想不到的错误结果。
#include<stdio.h>
#include<string.h>
int main(){
char c1[20]="program",c2[10]="example";
strcpy(c1, c2);
printf("String C1:");
puts(c1);
printf("String C2:");
puts(c2);
}
c2直接覆盖掉c1
如果我去掉example后的ple看看结果是怎样的?
结果是完全覆盖
模拟一下计算机执行的过程
#include<stdio.h>
void myStrcpy(char c1[],char*c2){
char *t=c2;
for(int i=0;*t!='\0';i++,t++)
c1[i]=*t,c1[i]='\0';
}
这段代码无法运行,但是能看出这个机器整个运行的过程
字符串比较函数:strcmp()
格式:strcmp(s1,s2)
功能:比较字符串s1和字符串s2的大小
说明
>自左至右逐个字符比较字符串中个字符的ASCII码值
>遇到不同字符或'\0'时,比较过程结束,此时,ASCII码值大的字符所在的字符串大
>strcmp()函数的返回一个数值
s1==s2:值为0
s1>s2:正数
s1<s2:负数
//实例,允许密码试三次
#include<stdio.h>
#include<string.h>
#define N 3
int main(){
int count=1;
char word[20];
printf("please put into the word");
gets(word);
while(count++<=N){
if(strcmp(word,'12345678')==0)
break;
}
if(count>N+1)
printf("Sorry");
else
printf("continue");
}
//第五章数组程序设计02
//strcmp具体事例
#include<stdio.h>
#include<string.h>
int myStrcmp(char *c1,char *c2){
char *t1=c1,*t2=c2;
for (t1!='\0'&&*t2!='\0'&&*t1==*t2;t1++,t2++)
if(*t1=='\0'&&t2=='\0') //if(*t1==*t2)
return 0;
if(*t1>*t2)
return 1;
return -1;
}
函数及用法 | 功能 | 说明 |
strlwr(s) | 将字符串s中的大写字母转换为小写字母的函数 | s可以是字符数组名(字符串首地址),也可以是字符串常量。 |
strupr(s) | 将字符串s中的小写字母转换为大写字母的函数 | |
strlens(s) | 求字符串s的长度 |
lower大写转换成小写
uper小写转换成大写
length字符串中字符的个数