字元數組:存儲字元的數組
字元串 :是使用最頻繁的字元數組,是一個特殊的字元數組
C++中并沒有專門的字元串的類型,一個字元串實際上就是一個字元數組,與普通字元數組不同的是,字元串的結尾有一個字元\0,表示字元串的結束。
char 可以定義字元數組,也可以定義字元串
char 定義的字元數組
char b[]={'h','e','l','l','o'};//生命字元數組,長度為5
- 1
char定義字元串
字元串的優勢在于輸入、輸出和賦初值,輸入輸出不需要使用循壞。字元數組需要用循環依次輸出每個字元。
char b[]="hello";//定義字元串
char *p = b;
cout << b;//輸出的是hello
cout<< *p;//指針指向首位址,是以輸出為 h
- 1
- 2
- 3
- 4
字元數組和字元串的差別
C++中,字元數組和字元串都是通過char關鍵字來定義的,但二者不同,顯著的差別就是字元串的長度是字元數目加1,因為包含了\0結束符,而字元數組的長度就是字元的數目。對于字元數組可以通過sizeof求出其長度,但是對于字元串是其長度加上1。是以這個長度沒有意義,為此C++可以用strlen求出字元串的有效内容的長度(不含字元串結束辨別\0)。
指針與字元串、指針與字元數組
指針指向字元數組
char b[] = { 'h','e','l','l','o' };
char *pchar = b;
cout << *pchar;//該語句輸出 h
//cout << b; //不要用這個方式輸出,輸出的是 hello加一些亂碼字
cout << b[]; //該語句輸出 h
- 1
- 2
- 3
- 4
- 5
//以下語句實作用指針輸出hello。
for (size_t i = 0; i < 5; i++)
{
cout << *pchar;
pchar++;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
指針指向字元串
char定義的字元串
用char定義一個指針,并指向了char定義的字元串,那麼用指針變量p 和*p輸出的結果不一樣,請看一下兩種情況。 具體原因我也不知道。
方式1
char str[] = "we are poor students";//這是一個字元串
cout<<str<<endl;//輸出的是:we are poor students。這也是字元串的優點,可以整個輸出。
//指針通路每個字元并輸出。
char *p = str;
while (*p != '\0')
{
cout << *p;
p++;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
方式二
//
char *p = str;
while (*p != '\0')
{
cout << p<<endl;
p++;
}
以上語句輸出的結果是:
we are poor students
we are poor students
e are poor students
are poor students
are poor students
re poor students
e poor students
poor students
poor students
oor students
or students
r students
students
students
tudents
udents
dents
ents
nts
ts
s
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
string定義的字元串
這裡需要特别注意的是string并不是一個關鍵字,而是一個類。
下面代碼的指針指向的是對象,而不是string中的第一個字元。
string str="hello world";
string *p1 = &str; //注意必須加取位址運算符 &
cout << str << "," << *p1; //輸出的是 hello world,hello world
- 1
- 2
- 3
- 如果想通路string定義字元串中的每個字元,可以使用
str[i]
-
cout<<p1[0];//輸出的是 hello world
- 不可像char定義的字元串那樣使用p1[i],在string中,i>0并未配置設定指針,這種了解方式本來就錯誤。
用指針周遊 每個字元
- 用C++的疊代器
string str1 = "we are poor students";
for (string::iterator p1 = str1.begin(); p1 !=str1.end(); p1++)
{
cout << *p1 ;
}
- 1
- 2
- 3
- 4
- 5
- 用
轉化為c類型的string,如下代碼所示:c_str() (Get C string equivalent)函數
string str1 = "we are poor students";
const char *p = str1.c_str();//這句是關鍵。
for (size_t i = ; i < str1.size(); i++)
{
cout << *(p + i);
}