嗨,大家好!所以,作为程序员,我们经常处理各种数据类型的数组。今天的文章将涵盖C++字符串数组。
声明C++字符串数组的方式

1. 使用String关键字在C++中创建字符串数组
C++ provides us with ‘string’ keyword to declare and manipulate data in a String array.
string关键字
根据需要在动态或运行时为数组元素分配内存。因此,它避免了对数据元素进行静态内存分配的麻烦。
语法:使用’string’关键字声明字符串数组
string array-name[size];
此外,我们可以使用以下语法初始化字符串数组:
string array-name[size]={'val1','val2',.....,'valN'};
示例1:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string fruits[5] = { "Grapes", "Apple","Pineapple", "Banana", "Jackfruit" };
cout<<"String array:\n";
for (int x = 0; x< 5; x++)
cout << fruits[x] << "\n";
}
在上面的例子中,我们初始化了字符串数组,并使用C++ for循环遍历数组并打印字符串数组中的数据项。
输出:
String array:
Grapes
Apple
Pineapple
Banana
Jackfruit
示例2:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string arr[5];
cout<<"Enter the elements:"<<endl;
for(int x = 0; x<5;x++)
{
cin>>arr[x];
}
cout<<"\nString array:\n";
for (int x = 0; x< 5; x++)
cout << arr[x] << "\n";
}
正如大家所见,在上面的例子中,我们接受了字符串数组的数据项,这些数据项来自控制台,即用户输入被获取,然后我们打印了字符串数组中的元素。
输出:
Enter the elements:
Jim
Nick
Daisy
Joha
Sam
String array:
Jim
Nick
Daisy
Joha
Sam
2. 使用C++ STL容器 – 向量
C++ Standard Template Library provides us with containers to work with data and store it efficiently.
向量是这样一种容器,以动态方式存储数组元素。因此,C++向量可以用于创建字符串数组并轻松地操作它们。
语法:
vector<string>array-name;
-
vector.push_back(element)
方法用于向向量字符串数组添加元素。 -
vector.size()
方法用于计算数组的长度,即输入到字符串数组中的元素的数量。
示例:
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<string> arr;
arr.push_back("Ace");
arr.push_back("King");
arr.push_back("Queen");
int size = arr.size();
cout<<"Elements of the vector array:"<<endl;
for (int x= 0; x< size; x++)
cout << arr[x] << "\n";
}
输出:
Elements of the vector array:
Ace
King
Queen
3. 使用二维字符数组
A 2D array represents an array of string in C++. So, we can use a 2D char array to represent string type elements in an array.
字符数组在静态或编译时创建和存储元素,即元素的数量和大小保持不变/固定。
语法:
char array-name[number-of-items][maximun_size-of-string];
示例:
#include <bits/stdc++.h>
using namespace std;
int main()
{
char fruits[5][10] = { "Grapes", "Apple","Pineapple", "Banana", "Jackfruit" };
cout<<"Character array:\n";
for (int x = 0; x< 5; x++)
cout << fruits[x] << "\n";
}
在上面的代码片段中,我们创建了一个字符数组来存储字符串类型的元素。即 char array[5][10]。这里的5表示字符串元素的数量,10指的是输入字符串的最大大小。
输出:
Character array:
Grapes
Apple
Pineapple
Banana
Jackfruit
C++ String Array as an Argument to a Function
A string array can also be passed to a function as an argument the same way as another non-string type array is passed to it.
语法:
return-type function-name(string array-name[size])
{
// 函数的主体
}
示例:
#include <iostream>
#include<string>
using namespace std;
void show(string arr[4]){
for(int x=0;x<4;x++)
{
cout<<arr[x]<<endl;
}
}
int main() {
string arr[4] = {"Jim", "Jeo", "Jio", "John"};
cout<<"Printing elements of the string array:"<<endl;
show(arr);
}
输出:
Printing elements of the string array:
Jim
Jeo
Jio
John
结论
在本文中,我们了解了创建字符串数组的方法以及在函数中使用它的技巧。
参考资料
Source:
https://www.digitalocean.com/community/tutorials/string-array-in-c-plus-plus