一、string字符串比较
比较方式: 字符串比较是按字符的ASCII码进行对比
= 返回 0 > 返回 1 < 返回 -1
函数原型:
int compare(const string &s) const; //与字符串s比较
int compare(const char *s) const; //与字符串s比较
代码示例:
#include<iostream>
using namespace std;
#include<string>
void test()
{
string str1 = "hello";
string str2 = "xello";
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()
{
test();
return 0;
}
二、string字符存取
函数原型:
char& operator[](int n); //通过[]方式取字符
char& at(int n); //通过at方法获取字符
代码示例:
#include<iostream>
using namespace std;
#include<string>
//string 字符存取
void test()
{
string str = "hello";
//cout << "str = " << str << endl;
//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()
{
test();
return 0;
}
三、string插入和删除
函数原型:
string& insert(int pos, const char* s); //插入字符串
string& insert(int pos, const string& str); //插入字符串
string& insert(int pos, int n, char c); //在指定位置插入n个字符c
string& erase(int pos, int n = npos); //删除从Pos开始的n个字符
代码示例:
#include<iostream>
using namespace std;
#include<string>
void test()
{
string str = "hello";
//插入
str.insert(1, "111");
//h111ello
cout << "str = " << str << endl;
//删除
str.erase(1, 3);
cout << "str = " << str << endl;
}
int main()
{
test();
return 0;
}
四、string子串
函数原型:
string substr(int pos = 0, int n = npos) const; //返回由pos开始的n个字符组成的字符串
代码示例:
#include<iostream>
using namespace std;
#include<string>
void test01()
{
string str = "abcdef";
string subStr = str.substr(1, 3);//bcd
cout << "subStr = " << subStr << endl;
}
//实用操作
void test02()
{
string email = "zhangsan@sina.com";
//从邮箱地址中获取用户名信息
int pos = email.find("@");//8
string usrName = email.substr(0, pos);
cout << usrName << endl;
}
int main()
{
//test01();
test02();
return 0;
}