//例题10-15 定义一个字符数组,对它初始化,然后输出该字符串#include<stdio.h>intmain(){char str[]="I love China!";printf("%s\n",str);return0;}
例题10-16 定义字符指针
//例题10-16 定义字符指针 #include<stdio.h>intmain(){char*str="I love China!";//<==>char *str; str="I love China!"printf("%s\n",str);return0;}
例题10-17 将字符串a复制为字符串b
//例题10-17 将字符串a复制为字符串b#include<stdio.h>intmain(){char a[]="I am a boy.",b[20];int i;for(i=0;*(a+i)!='\0';i++)*(b+i)=*(a+i);*(b+i)='\0';printf("string a is: %s\n",a);printf("string b is: ");for(i=0;b[i]!='\0';i++)printf("%c",b[i]);printf("\n");return0;}
例题10-18 用指针变量来处理例题10-17问题
//例题10-18 用指针变量来处理例题10-17问题#include<stdio.h>intmain(){char a[]="I am a boy.",b[20],*p1,*p2;int i;
p1=a;//指针变量p1,p2
p2=b;for(;*p1!='\0';p1++,p2++)*p2=*p1;*p2='\0';printf("string a is: %s\n",a);printf("string b is: ");for(i=0;b[i]!='\0';i++)printf("%c",b[i]);printf("\n");return0;}
数组可以在定义时整体赋初值,但不能在赋值语句中整体赋值
char str[14];
str[]="I love China!";//错误!
例题10-19 用函数调用实现字符串的复制
//例题10-19 用函数调用实现字符串的复制#include<stdio.h>voidcopy_str(char f[],char t[]){int i=0;while(f[i]!=0){
t[i]=f[i];
i++;}
t[i]='\0';}intmain(){char a[]="I am a student.";char b[]="You are a teacher.";copy_str(a,b);printf("string a = %s\nstring b = %s\n",a,b);return0;}
使用指针变量,做例题10-19
#include<stdio.h>voidcopy_str(char f[],char t[]){int i=0;while(f[i]!=0){
t[i]=f[i];
i++;}
t[i]='\0';}intmain(){char a[]="I am a student.";char b[]="You are a teacher.";char*a1=a,*b1=b;//使指针变量a1,b1,指向字符串 copy_str(a1,b1);printf("string a = %s\nstring b = %s\n",a,b);return0;}
形参用字符指针变量,做例题10-19
#include<stdio.h>voidcopy_str(char*f,char*t)//形参用字符指针变量 {for(;*f!='\0';f++,t++)*t=*f;*t='\0';}intmain(){char a[]="I am a student.";char b[]="You are a teacher.";char*a1=a,*b1=b;//使指针变量a1,b1,指向字符串 copy_str(a1,b1);printf("string a = %s\nstring b = %s\n",a,b);return0;}
例题10-20 改变指针变量的值
//例题10-20 改变指针变量的值#include<stdio.h>intmain(){char*a="I love China!";
a=a+7;//从 原始字符串的第7个字符开始,后边所有的 printf("%s",a);return0;}//输出 China!
例题10-21 用带下标的字符指针变量引用字符串中的字符
//例题10-21 用带下标的字符指针变量引用字符串中的字符#include<stdio.h>intmain(){char*a="I love China!";for(int i=0;a[i]!='\0';i++)printf("%c",a[i]);return0;}