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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM