C++字符串各種用法講解
大家知道,C++編程語言中,對(duì)于字符串的操作是一個(gè)比較基礎(chǔ)而且重要的操作技巧。C++字符串一般情況下可以通過以下兩種形式進(jìn)行表示,分別為;傳統(tǒng)字符串,以及字符數(shù)組這兩種。#t#
1.C++字符串之 傳統(tǒng)字符串
a) char ch1[] = {“liangdiamond”}
b) char ch2[] = {“hello world”}
其中關(guān)于傳統(tǒng)字符串,有幾個(gè)常用的函數(shù)
a) strcpy()函數(shù)
b) strcat()函數(shù)
c) strlen()函數(shù)
d) strcmp()函數(shù)
e) strlwr()函數(shù):大寫變?yōu)樾?/p>
f) strupr()函數(shù),小寫變?yōu)榇髮?/p>
2. C++字符串之字符數(shù)組
從表面上看,一個(gè)字符串是一個(gè)字符數(shù)組,但在c++語言中,它們不同。字符串是以’\0’結(jié)束的字符型數(shù)組。下面這段代碼展示字符串和字符數(shù)組的區(qū)別:
- #include < iostream>
- using namespace std;
- int main()
- {
- char a[] = {"hello"};
- char b[] = {'h','e','l','l','o'};
- int la = 0;
- int lb = 0;
- cout< < "The length of a[]:"< < sizeof(a)/sizeof(char)< < endl;
- cout< < "The length of b[]:"< < sizeof(b)/sizeof(char)< < endl;
- system("Pause");
- return 0;
- }
可以修改程序:
- #include < iostream>
- using namespace std;
- int main()
- {
- char a[] = {"hello"};
- char b[] = {'h','e','l','l','o','\0'};
- int la = 0;
- int lb = 0;
- cout< < "b="< < b< < endl;
- cout< < "The length of a[]:"< < sizeof(a)/sizeof(char)< < endl;
- cout< < "The length of b[]:"< < sizeof(b)/sizeof(char)< < endl;
- system("Pause");
- return 0;
- }
但是數(shù)組名就是數(shù)組的首地址,所以數(shù)組名本身就可以理解為一個(gè)指針,只不過,它是指針常量,所謂指針常量,就是指針不能改變所指向的地址了,但是它所指向的地址中的值可以改變。
例如:
- #include < iostream>
- using namespace std;
- int main()
- {
- char a[] = {"hello"};
- char b[] = {'h','e','l','l','o','\0'};
- a++;
- system("Pause");
- return 0;
- }
編譯報(bào)錯(cuò)。
C++字符串中字符數(shù)組和字符指針雖然在形式上很接近,但在內(nèi)存空間的分配和使用上還是有很大差別。數(shù)組名不是一個(gè)運(yùn)行時(shí)的實(shí)體,因此數(shù)組本身是有空間的,這個(gè)空間由編譯器負(fù)責(zé)分配。而指針是一個(gè)變量(運(yùn)行時(shí)實(shí)體),它所指向的空間是否合法要在運(yùn)行時(shí)決定。
- #include < iostream>
- using namespace std;
- int main()
- {
- char s[] = "abc";
- char* p = "abc";
- s[0] = 'x';
- cout< < s< < endl;
- //p[0] = 'x'; 編譯報(bào)錯(cuò)
- cout< < p< < endl;
- system("Pause");
- return 0;
- }
S的地址和p所指向的地址并不是一個(gè)地方,可以推斷0x00417704是常量區(qū)。所以貌似不能改。用反匯編其實(shí)看的更清楚一點(diǎn)。指針好就好在它能指向內(nèi)存,不是ROM 區(qū)的好似都能改。
以上就是對(duì)C++字符串的相關(guān)介紹。