6.4字将串写指针 1.用字符数组存放一个字符串 例:定义一个字符数组并初始化,然后输出 其中的字符串。 #include <iostream> using namespace std; int main() char str[]="I love CHINA!"; cout<<str<<endl; return O; }
6.4 字符串与指针 1. 用字符数组存放一个字符串 例: 定义一个字符数组并初始化,然后输出 其中的字符串。 #include <iostream> using namespace std; int main( ) { char str[]=″I love CHINA!″; cout<<str<<endl; return 0; }
6.4字将串写指针 2.用字符串变量存放字符串 例:定义一个字符串变量并初始化,然后输 出其中的字符串。 #include <string> #include <iostream> using namespace std; int main( string str="I love CHINA!"; cout<<str<<endlj return O; }
6.4 字符串与指针 2. 用字符串变量存放字符串 例: 定义一个字符串变量并初始化,然后输 出其中的字符串。 #include <string> #include <iostream> using namespace std; int main( ) { string str=″I love CHINA!″; cout<<str<<endl; return 0; }
6,4字将串与指针 3.用字符指针指向一个字符串 例:定义一个字符指针变量并初始化,然后输 出它指向的字符串。 #include <iostream> using namespace std; int main() char *str="I love CHINA!" cout<<str<<endl; return O; } 对字符串中字符的存取,可以用下标方法, 也可以用指针方法
6.4 字符串与指针 3. 用字符指针指向一个字符串 例:定义一个字符指针变量并初始化,然后输 出它指向的字符串。 #include <iostream> using namespace std; int main( ) { char *str=″I love CHINA!″; cout<<str<<endl; return 0; } 对字符串中字符的存取,可以用下标方法, 也可以用指针方法
6,4字将串与指针 例:将字符串str1复制为字符串str2。 #include <iostream> using namespace std int main() char str1[]="I love CHINA!", str2[20],*p1,*p2; p1=str1;p2=str2; for(*p1I=\0'p1++,p2++) *p2=*p1; *p2=\0: p1=str1ip2=str2; cout<<"str1 is:"<<p1<<endl; cout<<"str2 is:"<<p2<<endlj return O;
6.4 字符串与指针 例: 将字符串str1复制为字符串str2。 #include <iostream> using namespace std; int main( ) { char str1[]=″I love CHINA!″, str2[20],*p1,*p2; p1=str1;p2=str2; for(;*p1!=′\0′;p1++,p2++) *p2=*p1; *p2=′\0′; p1=str1;p2=str2; cout<<″str1 is: ″<<p1<<endl; cout<<″str2 is: ″<<p2<<endl; return 0; }
6,5品数与指针 用函数指针变量调用函数 例:求a和b中的大者。先按一般方法写程序: #include <iostream> using namespace std; int main() {int max(int x,int y); int a,b,m; cin>>a>>b;m=max(a,b); cout<<"max="<<m<<endl; return O;} int max(intx,inty) {int z; if(x>y)z=xi else z=yi return(z);}
6.5 函数与指针 一、 用函数指针变量调用函数 例:求a和b中的大者。先按一般方法写程序: #include <iostream> using namespace std; int main( ) {int max(int x,int y); int a,b,m; cin>>a>>b;m=max(a,b); cout<<″max=″<<m<<endl; return 0;} int max(int x,int y) {int z; if(x>y) z=x; else z=y; return(z);}