一、字符串的概念和字符數組
字符串是由一系列字符組成的,其中最後一個字符為’\0’(末尾符)。C++中沒有專門的字符串類型,但是可以用字符數組來表示字符串。
字符數組是C++中一種基本類型的數組,它的元素是字符類型,常用於表示字符串。C++中可以直接使用字符數組進行字符串的各種操作。
char str[] = "hello world";
二、字符數組的初始化和賦值
字符數組可以通過定義字符數組變量來初始化,也可以通過賦值來初始化。字符數組的賦值可以通過一個字符串常量或另外一個字符數組進行。
使用字符串常量初始化字符數組:
char str1[] = "hello world";
使用一個字符數組初始化另外一個字符數組:
char str2[20]; char str3[] = "hello world"; for (int i=0; i<strlen(str3); i++) { str2[i] = str3[i]; }
三、字符數組的長度和遍歷
可以使用C++標準庫中的strlen函數來獲取字符數組的長度:
char str[] = "hello world"; int len = strlen(str);
使用循環遍歷字符數組中的每一個元素:
for (int i=0; i<strlen(str); i++) { cout << str[i] << endl; }
四、字符串操作
C++中可以利用字符數組進行字符串的各種操作,例如以下操作:
- 字符串比較
- 字符串拼接
- 字符串複製
五、字符串比較
C++中提供了strcmp函數來對兩個字符串進行比較,它將兩個字符串作為參數傳遞進去,返回值為0、正整數或者負整數:
char str1[] = "hello"; char str2[] = "world"; if (strcmp(str1, str2) == 0) { cout << "str1 equals str2" << endl; } else if (strcmp(str1, str2) < 0) { cout << "str1 is smaller than str2" << endl; } else { cout << "str1 is larger than str2" << endl; }
六、字符串拼接
C++中提供了strcat函數對兩個字符串進行拼接,它將兩個字符串作為參數傳遞進去,返回值為第一個字符數組的地址:
char str1[20] = "hello"; char str2[] = "world"; strcat(str1, str2); cout << str1 << endl;
七、字符串複製
C++中提供了strcpy函數對一個字符串進行複製,將一個字符數組作為參數傳遞進去,返回值為目標字符數組的地址:
char str1[] = "hello"; char str2[20]; strcpy(str2, str1); cout << str2 << endl;
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/244810.html