7.18

发布时间 2023-07-18 14:52:39作者: a_true

c++ string操作

#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;
void main()
{
/*构造函数*/
string str1; //默认构造函数
string str2("abc"); //传入string或者c_str
string str3(4, 'a'); //4个字符a构建成string
string str4(str2, 1); //从str2的位置1开始构造
string str5(str2.begin(), str2.end()); //从str2的迭代器开始构造
cout << str2 << endl << str3 << endl<< str4 << endl<<str5<<endl;
}

增:

string str1("str1");
string str2("str2");
str1 += str2;
cout << str1 << endl;

 

string str1("str1");
str1.append("123"); //直接添加字符串至尾部
cout << str1 << endl;
str1.append("1230", 2); //从参数字符串起始位置开始添加2个字符到str1
cout << str1 << endl;
string str2("str2");
str1.append(str2, 0, 1); //把str2的区间[0,1)的字符添加至str1
cout << str2 << endl << str1 << endl;

 

string str1("str1");
str1.push_back('a');
cout << str1 << endl;

 

string str1("str1");
str1.insert(0, "insert"); //从0开始插入参数字符串
cout << str1 << endl;
str1.insert((string::size_type)0, 2, '0'); //在指定位置插入2个'0',用size_type强转不会产生歧义
cout << str1 << endl;
str1.insert(str1.begin(), 3, 'b'); //迭代器指定位置后面插入3个'b'
cout << str1 << endl;

删:

string str1("string1");
str1.erase(0, 1); //删除指定区间
cout << str1 << endl;
str1.erase(2); //指定删除的起始位置,直至末尾
cout << str1 << endl;

 

string str1("string1");
str1.pop_back(); //从尾部弹出字符
cout << str1 << endl;

 

str1.clear();//清空字符串,使字符串为空

改:

string str1("string1");
str1.replace(0, 2, "rep"); //把指定区间的字符替换成参数字符串
cout << str1 << endl;
str1.replace(0, 2,"123",2);//把指定区间的字符替换成参数字符串的前面2个
cout << str1 << endl;
str1.replace(0, 2, "456", 0, 3); //把指定区间的字符替换成参数字符串指定的区间字符
cout << str1 << endl;

查:

cout << str1.at(1) << endl;//某个位置的字符

 

string str1("string1string1");
cout << str1.find('i') << endl; //查找某个字符位置
int idx=str1.find('2'); //不存在返回string::npos,-1
cout << idx << endl;
cout<<str1.find("ta")<<endl; //匹配查找字符串的位置,
cout << str1.find("ng", 10)<<endl; //从指定位置开始匹配
cout << str1.find_first_of("ta")<<endl; //从前面往后匹配参数字符串中的字符的第一个字符
cout << str1.find_last_of("tn") << endl;//从后面往前匹配参数字符串的字符
cout << str1.find_first_not_of("ta") << endl;//与find_first_of相反
cout << str1.find_last_not_of("g1") << endl;//与find_last_of相反

切割字符串:

string str1("string1string1");
string temp = str1.substr(0, 2); //指定区间的字串
cout << temp << endl;
string temp2 = str1.substr(1); //从指定位置开始切割至尾部
cout << temp2 << endl;

字符串和数字转换:

string str1("124");
cout << stoi(str1) << endl; //转为整数
cout << stof(string("124.3")) << endl;//转为浮点型
string str = to_string(124); //数字转为字符串
cout << str << endl;
str = to_string(13.4);
cout << str << endl;