string这个字符串类型我是很喜欢的(主要是方便),这篇给大家讲一下string基础的一些使用方法
一.定义
string s;
这就是最基本的定义(也没其他的了。。。)
这里s是变量名,是一个字符串类型(我觉得比char的字符串简单)
二.输入输出
输入:cin>>s;
输出:cout<<s;(想不到吧,我也想不到。。。)
三.string特性
字符串下标由0——n-1(n为\0),因此在得到字符串长度时要小心
大小会比char小一点,所以如果字符串过长,不建议使用
四.配合string的函数
1.获取长度: .length()
用法:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
int len=s.length();
cout<<len;
}
2.含空格输入 getline(cin, )
用法:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin, s);
cout<<s;
}
3.查找 .find()
会返回找到的括号内的字符/变量/字符串第一次出现时的下标
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin, s);
int f=s.find("d");
cout<<f;
return 0;
}
想要得到最后一次出现这个字符的下标,就需要改进一下:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin, s);
int f=s.find_last_of("d");
cout<<f;
return 0;
}
注意:它返回的是下标,是在字符串中的位置-1
如果字符串中没有这个字符(串),会返回-1(string::npos)
4.从……开始输出 .substr( , )
用法:从下标为……开始输出,输出……个数
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin, s);
cout<<s.substr(2, 3);
return 0;
}
到这里就差不多了,有些累了,string的基本用法都讲了的,够用一阵子的了~