指向字符串的指针变量
❖}
❖ encrypt(char *s)
❖ { for(; _*s_!=‘_\0’ ;s++)
❖
if(*s==‘z’)
❖
_ _ _*s=_‘a’_ _ _ _ _
❖
else
❖
_ _*_s=*_s+_1; _ _ _ _
❖}
❖
作业:
❖ 练习册p121-124
❖
void strcpy(char *p,char *q)
❖
{ while(*q!=‘\0’)
❖
{ *p=*q;
❖
p++;
❖
q++;
❖
}
❖
}
典型例题2:编写程序输出以下图形
❖ 用字符数组实现
❖
#include<stdio.h>
❖
main()
❖
{ char s[ ]=“*****”;
❖
int i;
❖
4、要处理字符串中的单个字符,则通过数组下标或者字符
指针的间接访问。
但是两个定义的差别很大:
char ch[ ] 定义一个数组,ch是一个足以存放字 符串和空字符‘\0’的一维数组的名字,也是首地址, 它是一个常量,一旦定义,即使该数组中存储的字符 串发生改变,它也不发生变化,总是指向同一存储区。
例如: char *p=“abc” ; printf(“%c\n”,*p);
p
a
p+1
b
p+2
c
printf(“%s\n”,p);
\0
printf(“%s” ,p+1);
输出结果为:
a
abc
注意:
bc
1、赋值时,字符串的结束标志‘\0’是系统自动增加的。 2、字符串在内存中连续存放。
3、在输出/输入字符串时,如果只指出数组名或者指针变量, 则是处理整个数组。
for (i=0;s[i]!=‘\0’;i++)
❖
printf(“%s\n”,s+i);
❖
}
***** **** *** ** *
用字符指针实现
❖
#include<stdio.h>
❖
main()
❖
{ char *p=“*****”;
❖
for(;*p;)
❖
printf(“%s\n”,p++);
❖
}
思考:
❖ main()
❖ { char line[MAXLINE];
❖ printf(“Input the string:”); ❖ _ge_ts(l_ine_); _ _ _ _ _
❖ encrypt(line);
❖ printf(“%s%s\n”,”After being encrypted:”,line);
❖ 编写程序输出以下图形:
❖
*
❖
**
❖
***
❖
****
❖
*****
❖
#include<stdio.h>
❖
main()
❖
{ char *p=“*****”,*q;ቤተ መጻሕፍቲ ባይዱ
❖
for(q=p+4;q>=p;q--)
❖
printf(“%s\n”,q);
❖
}
学生练习:
❖
#include<stdio.h>
❖
#include<string.h>
•字符串的两种表示形式:
1、字符数组的方式实现: char ch[ ]=“this is a book!” ;
使用数组的下标可以逐个访问字符串中 的字符,还可以用%s格式整体输入输出 例如:
for(i=0;ch[i]!=‘\0’;i++) printf(“%c”,ch[i]);
printf (“%s\n” ,ch);
❖}
运行结果: 976531
为了防止信息被别人轻易窃取,需要把电
码明文通过加密方式变换成密文。变换规 则如下:小写z变为a,其它字母变换为该 字母ASCII码顺序后1位的字母,比如Q变
换为P.
❖ #include<stdio.h>
❖ #include<string.h>
❖ #define MAXLINE 100
char *p中的 p是一个指针,其初值指向一个字符 串常量,它存放的是该字符串的首地址(并不是该字 符串的内容),之后它还可以被修改指向其他字符串, 那么它就改为指向其它存储区,值随之发生变化。
例:若字符数组mess和指向字符串的指针变量p的内 容发生了变化,测试mess和p的值是否发生变化。
❖ #include<stdio.h> ❖ char mess[]=“I am a student”; ❖ char *p=“China”; ❖ int i; ❖ main() ❖ { printf(“%d,%d\n”,mess,p); ❖ p=“Fuzhou”; ❖ i=0; ❖ while(mess[i]!=‘\0’) ❖ { mess[i]=mess[i+1]; i++;} ❖ printf(“%d,%d\n”,mess,p); ❖}
❖
}
❖ main()
❖ { char s[]=“97531”,c;
❖ c=‘6’;
❖ fun(s,c);
❖ puts(c);
❖}
❖ fun(char *a,char b)
❖ { while(*(a++)!=‘\0’);
❖ while(*(a-1)<b)
❖
*(a--)=*(a-1);
❖ *(a--)=b;
❖ 2、字符指针的方式实现: char *p=“this is a book!” ;
使用字符指针的间接访问运算符可以逐个 访问字符串中的字符,也可以使用%s格式 对字符串整体输入输出。 例如: for(;*p!=‘\0’;p++)
printf(“%c”,*p);
printf (“%s\n” ,p);
❖
main()
❖
{ int i=0,n=0;
❖
char s[80],*p;
❖
p=s;
❖
strcpy(p,”It is a book.”);
❖
for(;*p!=‘\0’;p++)
❖
if(*p==‘ ’) i=0;
❖
else if(i==0)
运行结果:n=4
❖
{n++;i=1;}
❖
printf(“n=%d\n”,n);
运行结果为: 404,421 404,434
典型例题1:编写字符串复制函数strcpy(s1,s2)
❖ 用数组实现
❖
❖ void strcpy(char s1[ ],char s2[ ])
❖
{ int i=0;
❖
while(s2[i]!=‘\0’)
❖
{ s1[i]=s2[i];
❖
i++;
❖
}
❖
}
用指针实现