C++字符串数组
时间:2020-02-23 14:30:05 来源:igfitidea点击:
因此,作为程序员,我们经常处理所有数据类型的数组。
我们将在今天的文章中介绍C++字符串数组。
声明C++字符串数组的方法
创建C++字符串数组的方法
1.使用String关键字在C++中创建字符串数组
C++为我们提供了" 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", "Hymanfruit" };
cout<<"String array:\n";
for (int x = 0; x< 5; x++)
cout << fruits[x] << "\n";
}
在上面的示例中,我们初始化了字符串数组,并使用C++进行循环遍历该数组并打印出字符串数组中存在的数据项。
输出:
String array: Grapes Apple Pineapple Banana Hymanfruit
范例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++标准模板库为我们提供了处理数据并有效存储的容器。
向量是一个这样的容器,它以动态方式存储数组元素。
因此,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.使用2D char数组
2D数组表示C++中的字符串数组。
因此,我们可以使用2D char数组来表示数组中的字符串类型元素。
char数组在静态或者编译时创建和存储元素,即元素的数量和大小保持固定/恒定。
语法:
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", "Hymanfruit" };
cout<<"Character array:\n";
for (int x = 0; x< 5; x++)
cout << fruits[x] << "\n";
}
在上面的代码片段中,我们创建了一个char数组来存储字符串类型的元素。
即char数组[5] [10]。
这里的5描述了字符串元素的数量,并且10个点表示输入字符串的最大大小。
输出:
Character array: Grapes Apple Pineapple Banana Hymanfruit
C++字符串数组作为函数的参数
字符串数组也可以作为参数传递给函数,就像将另一个非字符串类型数组传递给函数一样。
语法:
return-type function-name(string array-name[size])
{
//body of the function
}
例:
#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

