#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
void test()
{
string s = "abcd";
//s += "ni";//重载
/*cout << s << endl;*///abcdni
char a[20] = "abncd";
s += (a);//拼接在字符串的后面
cout << s << endl;
}
void test2() //string拼接
{
string s = "abcde";
string s2 = "123";
//s.append(s2);//将s2放在s的后面 abcde123
s.append(s2,1);//将s2的前n个后 放到字符串s的末尾
cout << s << endl;
}
void test3() //string 查找 find从前往后找 rfind 最后一次出现的位置
{
string s = "abcdbc";
int pos =s.find("bc"); // 查找第一次出现的位置 理解为字符数组 a[0] ='a' [1] ='b' 下标为0
cout << pos+1 << endl; //按照惯性思维 第二个位置
int c = s.rfind("bc");
cout << c +1<< endl;
}
void test4()
{
string s = "abcdefg";
s.replace(3, 6, "wxhn");//从3开始的6个字符被替换
cout << s << endl;
string s = "abc";
s.replace(0, 2, "11");//从0开始的两个字符被替换
cout << s << endl;
}
void test5()
{
string s = "lynlyn";
string s2 = "yxj";
int num = s.compare(s2);//作比较 逐个字符作比较 s比s2大返回1 s比s2小返回-1 相等返回0
cout << num << endl;
}
void test6()
{
//string substr(int pos =0,int n = npos)const 返回由pos开始第n个字符组成的字符串
string s = "abcdefg";
string n = s.substr(0, 3);//从0开始3个字符
cout << n << endl;
}
void test7()
{
string s = "123456";
s.insert(2, "abc");
cout << s << endl;
s.insert(2, "111");//从2号位置前插入111 把改位置往后移 这个字符串插在他的前面 前插
cout << s << endl;//121113456
s.erase(0, 2);//从0号位开始删除两个
cout << s << endl; //1113456
}
int main()
{
test7();
return 0;
}
C++中string的一些操作
最新推荐文章于 2024-07-25 12:39:48 发布