c++字符串数组
时间: 2023-07-09 11:09:15 浏览: 84
在 C++ 中,字符串数组可以通过以下方式声明:
```c++
char strArray[5][20]; // 声明一个包含 5 个长度为 20 的字符串的数组
```
其中,`char` 表示字符类型,`strArray` 是数组名,`[5]` 表示数组长度为 5,`[20]` 表示每个字符串的长度为 20。
我们可以通过下标访问数组中的每个字符串,例如:
```c++
strArray[0] = "Hello";
strArray[1] = "World";
```
注意,在 C++ 中,字符串是以 null 结尾的字符数组。因此,我们需要在字符串数组中为每个字符串留出一个额外的空间,存储 null 字符。
相关问题
c++字符串数组初始化
在C++中,可以使用字符串数组来存储多个字符串。有几种方法可以初始化C++字符串数组:
1. 使用初始化列表:
```cpp
string arr[] = {"string1", "string2", "string3"};
```
2. 逐个赋值:
```cpp
string arr;
arr = "string1";
arr = "string2";
arr = "string3";
```
3. 使用循环赋值:
```cpp
string arr;
for (int i = 0; i < 3; i++) {
cout << "Enter string " << i+1 << ": ";
cin >> arr[i];
}
```
这些方法都可以用来初始化C++字符串数组。你可以根据具体的需求选择适合的方法。
c++ 字符串数组定义
C++中定义字符串数组有多种方式,以下是两种常见的方法:
方法一:使用字符串字面值初始化数组
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string array[3] = {"li", "zhang", "wang"};
for (int i = 0; i < 3; i++) {
cout << array[i] << endl;
}
return 0;
}
```
方法二:使用循环逐个赋值
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string array[3];
array[0] = "li";
array[1] = "zhang";
array[2] = "wang";
for (int i = 0; i < 3; i++) {
cout << array[i] << endl;
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)