string字符串比较/字符存取/插入和删除/子串获取

示例:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm> //标准算法的头文件
//字符串比较
void test01()
{
string str1="xello";
string str2="hello";
if (str1.compare(str2)==0)
{
cout<<"str1等于str2"<<endl;
}
else if (str1.compare(str2)>0)
{
cout<<"str1大于str2"<<endl;
}
else
{
cout<<"str1小于str2"<<endl;
}
}
int main()
{
test01();
return 0;
}
总结:
字符串对比主要是用于比较两个字符串是否相等,判断谁大谁小的意义并不是很大
string字符存取

示例:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm> //标准算法的头文件
//string 字符存取
void test01()
{
string str="hello";
//1、通过 []访问单个字符
for (int i = 0; i < str.size(); i++)
{
cout<<str[i]<<" ";
}
cout<<endl;
//2、通过at方式访问单个字符
for (int i = 0; i < str.size(); i++)
{
cout<<str.at(i)<<" ";
}
cout<<endl;
//修改单个字符
str[0]='x';
//xello
cout<<"str="<<str<<endl;
str.at(1)='x';
//xxllo
cout<<"str="<<str<<endl;
}
int main()
{
test01();
return 0;
}

总结:
string字符串中单个字符存取有两种方式,利用[]或at
string插入和删除

示例:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm> //标准算法的头文件
//字符串 插入和删除
void test01()
{
string str="hello";
//插入
str.insert(1,"111");
cout<<"str="<<str<<endl;
//删除
str.erase(1,3);
cout<<"str="<<str<<endl;
}
int main()
{
test01();
return 0;
}
总结:
插入和删除的起始下标都是从0开始
子串获取

示例:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm> //标准算法的头文件
//string求子串
void test01()
{
string str="abcdef";
string subStr=str.substr(1,3);
cout<<"subStr="<<subStr<<endl;
}
//实用操作
void test02()
{
string email="zhangsan@sina.com";
//从邮件地址中 获取 用户名信息
int pos=email.find("@");//8
string usrName=email.substr(0,pos);
cout<<"useName="<<usrName<<endl;
}
int main()
{
test01();
test02();
return 0;
}
总结:
灵活的运用求子串功能,可以在实际开发中获取有效的信息

浙公网安备 33010602011771号