一、string类(字符串)
#include<iostream>
#include<string>
using namespace std;
int main()
{
//创建字符串
string s{
"Hello" };
//clear
s.clear();
//用数组为字符串赋值
char arr[]{
'W','o','r','l','d' };
s += arr;
//assign()
s.assign("1024");
//append
s.append(" ");
s.append(5, '\t');
//s.append("!");
cout << s << endl;
//inset 空白
s.insert(0, " ");
//移除字符串前面的空白
s.erase(0, s.find_first_not_of(" \t\n\r"));
//移除字符串后面的空白
s.erase(s.find_last_not_of(" \t\n\r") + 1);
//把字符串转化为整数或浮点数
int x = std::stoi(s);
cout << s << endl;
cout << "x= " << x << endl;
string s2 = std::to_string(x);
cout << "s2 = "<<s2 << endl;
return 0;
}
得到结果如上图所示。
二、array类(数组)
#include<iostream>
#include<string>
#include<array>
#include<algorithm>
using std::cout;
using std::endl;
using std::array;
void print(array<int, 3>& a)
{
for (auto x:a)
{
cout << x << " ";
}
cout << endl;
}
int search(array<int, 3>& a, int token)
{
bool exist{
false };
int i = 0;
for (auto element : a)
{
if (element == token)
{
exist = true;
break;
}
i++;
}
if (exist)
return(i);
else
return(-1);
}
int main()
{
//1.创建数组
std::array a1{
1,2,4 };
print(a1);
cout << endl;
//2.为数组赋值
a1 = {
7,8,9 };
print(a1);
cout << endl;
//3.交换数组
array b1{
100,200,300 };
print(b1);
a1.swap(b1);
print(a1);
print(b1);
//4.求数组大小
cout << a1.size() << endl;
cout << a1.max_size() << endl;
//5.编写search函数,在数组中查找一个值
cout << "search 300: " << search(a1, 300) << endl;
cout << "search 1 :" << search(a1, 1) << endl;
//6.sort
std::sort(a1.rbegin(), a1.rend());
print(a1);
//7.二维数组
std::array<std::array<int, 3>, 4> a8;
return 0;
}
得到结果如上图所示。