C++字符串与指针 所有的内容也就这么多了。

1.定义一个字符串数组并初始化,然后输出其中的字符串。

#include <iostream>

using namespace std;
int main()
{
char str[]="i love china";
cout<<str<<endl;
return 0;
}

str是字符数组名,它代表字符数组的首元素的地址,输出时从str指向的字符开始,逐个输出字符,直到遇到‘\n’为止。

2.用字符串变量存放字符串。

定义一个字符串并初始化,然后输出其中的字符串。

#include <iostream>
#include<string>
using namespace std;
int main()
{
string str="i love china";
cout<<str<<endl;
return 0;
}

3.用字符指针指向一个字符串。

定义一个字符指针变量并初始化,然后输出它指向的字符串。

#include <iostream>
using namespace std;
int main()
{
char *str="i love china";
cout<<str<<endl;
return 0;
}

对字符指针变量str初始化,实际上是把字符串第1个元素的地址赋给str,系统输出时,先输出str所指向的第一个字符数据,然后使str自动加1,使之指向下一个字符,然后再输出一个字符。直到遇到字符串结尾标志‘\0’为止。注意,在内存中,字符串的最后被自动加了一个‘\0’,因此在输出时能确定字符串的终止位置。

4.通过指针来实现字符串的复制。

#include<iostream>
using namespace std;
int main(){
char str1[]="i love china";
char str2[20];
char *p1;
char *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;
}

 

posted @ 2015-01-24 15:31  深入理解C++和OpenCV  阅读(2542)  评论(0编辑  收藏  举报