目录
1.string赋值操作 :
2.string字符串拼接 :
#include<iostream>
using namespace std;
#include<string>
void test01()
{
string str1 = "我";
str1 += "是个帅哥";
cout << "str1=" << str1 << endl;
str1 += '!';
cout << "str1=" << str1 << endl;
string str2 = "真的很不错";
str1 += str2;
cout << "str1=" << str1 << endl;
string str3 = "我";
str3.append("喜欢");
cout << "str3=" << str3 << endl;
str3.append("game 接下来这句话没得", 4);
cout << "str3=" << str3 << endl;
//str3.append(str2);
//cout << "str3=" << str3 << endl;
str3.append(str2, 0, 4);
cout << "str3=" << str3 << endl;
}
int main()
{
test01();
}
3. string查找和替换
#include<iostream>
using namespace std;
#include<string>
//查找
void test01()
{
string str1 = "abcdeab";
int pos=str1.find("de");
if (pos == -1)
{
cout << "未找到字符串 pos=" << pos << endl;
}
else
{
cout << "pos=" << pos << endl;
}
/// <summary>
/// rfind从右往左,find从左往右
/// </summary>
pos = str1.rfind("ab");
cout << "pos=" << pos << endl;
}
//替换
void test02() {
string str1 = "abcdefg";
//第一个位置起,4个字符,替换成1111
str1.replace(1, 4, "1111");
cout << "str1=" << str1 << endl;
}
int main()
{
test01();
test02();
}
4.字符串比较: 主要用于,判断两个字符串是否相等
#include<iostream>
using namespace std;
#include<string>
//字符串比较
void test01()
{
string str1 = "Hello";
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();
}
5.string字符存取:
#include<iostream>
using namespace std;
#include<string>
//字符串比较
void test01()
{
string str = "hello";
//1.通过[]访问单个字符
cout << str[1] << endl;
for (int i = 0; i < str.size(); i++)
{
cout << str[i] << " ";
}
cout << endl;
//通过at访问
cout << str.at(1) << endl;
for (int i = 0; i < str.size(); i++)
{
cout << str.at(i) << " ";
}
cout << endl;
//1.通过[]修改单个字符
str[0] = 'x';
cout << str << endl;
//2.通过at修改
str.at(0) = 'h';
cout << str << endl;
}
int main()
{
test01();
}
6. 字符串插入和删除:
#include<iostream>
using namespace std;
#include<string>
//字符串 插入和删除
void test01()
{
string str = "hello";
str.insert(1, "111");
cout << str << endl;
str.erase(1, 3);
cout << str << endl;
}
int main()
{
test01();
}
7.获取子串:
#include<iostream>
using namespace std;
#include<string>
//获取子串
void test01()
{
string str = "abcdefg";
string substr = str.substr(0, 3);
cout << "str=" << str << endl;
cout << "substr=" << substr << endl;
}
//实际操作
void test02()
{
string qqemail = "1176894311@qq.com";
int pos = qqemail.find('@');
string subqq = qqemail.substr(0, pos);
cout <<"截取的id:"<< subqq << endl;
}
int main()
{
test01();
test02();
}