字符串字面值的類型就是const char類型的數組。
c風格字符串
c風格字符串既不能確切地歸結爲C語言的類型,也不能歸結爲c++類型,而是以空字符null結束的字符數組。
char ch1[] = { 'a', 'b', 'c' };
char ch2[] = { 'a', 'b', 'c', '\0' };
char ch3[] = "abc";
char *ch = ch2;
int main()
{
char s[] = "hello";
char *ps = s;
cout << s << endl;
cout << ps << endl;
while (*ps)//若*ps==null則循環終止
{
*ps = toupper(*ps);
++ps;
}
cout << s << endl;
//cout<<ps<<endl;注意此時輸出ps指向的字符串沒有意義,因爲ps指向的位置早已到了字符串末端的下一個位置
getchar();
return 0;
}
#include <cstring>
strlen(s)3.永遠不要忘記字符串結束符null
int main()
{
char ch[] = { 'a', 'b', 'c' };
char ch1[] = { 'a', 'b', 'c' ,'\0'};
cout << strlen(ch) << endl;
cout << strlen(ch1) << endl;
getchar();
return 0;
}
對於第一種輸出情況,結果是不確定的,strlen遍歷字符串,知道遇到空字符才停止,所以一定不要忘記空字符。int main()
{
char *ch1 = "hello";
char *ch2 = "world";
char ch3[20];
strncpy(ch3, ch1, 6);//複製ch1中6個字符到ch3,包括null
cout << ch3 << endl;
cout << strlen(ch3) << endl;//輸出ch3字符串的長度,不包括null
strncat(ch3," ", 2);//ch3連接兩個字符,一個空格,一個null字符,其中空格會覆蓋前面的null
cout << strlen(ch3) << endl;//共有7個字符,字符串的長度爲6
strncat(ch3, ch2, 6);//ch3連接ch2中6個字符,包括null,最前面的字符會覆蓋前面的null
cout << ch3 << endl;
cout << strlen(ch3) << endl;
getchar();
return 0;
}
int main()
{
int *p = new int[10]();
for (size_t index = 0; index != 10; ++index)
{
cout << p[index] << " ";
}
cout << endl;
getchar();
return 0;
}
int類型的默認值0,char類型的默認值空白字符(空格)const int *p=new int[10];//error
const int *p=new int[10]();//ok
const string *s=new string[10];//ok default construct function
3.允許動態分配空數組:
char ch[0];//error不允許創建0長度的數組
char *pc=new char[0];//ok
用new創建長度爲0的數組時,new返回有效的非零指針,該指針與new返回的其他指針不同,不能進行解引用操作,因爲他沒有指向任何對象,允許進行比較運算。int main()
{
int *p = new int[10];
for (size_t index = 0; index != 10; ++index)
{
p[index] = index;
cout << p[index] << " ";
}
cout << endl;
cout << p << endl;
delete[] p;
cout << p << endl;//空間釋放後,p指向的位置發生變化
getchar();
return 0;
}
int main()
{
char *s = "hello world";
string s1(s);//ok
string s2("hello world");//ok
cout << s << endl << s1 << endl;
cout << s << endl << s2 << endl;
getchar();
return 0;
}
2.在要求c風格字符串的地方不可直接使用標準庫string類型對象int main()
{
string s("hello world");
//char *p = s;//error
//char *p1 = s.c_str();c_str()返回const類型的c風格字符串
const char *p2 = s.c_str();
cout << p2 << endl;
getchar();
return 0;
}
c_str()返回const類型的c風格字符串。int main()
{
string s("hello world");
//char *p = s;//error
//char *p1 = s.c_str();
const char *p2 = s.c_str();
s = "hello";
cout << p2 << endl;
getchar();
return 0;
}
運行結果輸出helloint a[]={1,2,3,4,5,6};
vector<int> ivec(a,a+3);//1,2,3