c++笔试准备之string用法

1 头文件包含
#include

2 获取字符串的长度
string a=“sdgfbfnhdgfn”;
cout << a.length() << endl;
cout << a.size() << endl;
cout << strlen(a.c_str()) << endl;

3常用数字类型转字符串
cout << to_string(10) << endl;
cout << to_string(10.35) << endl;

4字符串转常用数字类型
string b = “123456”;
cout << atoi(b.c_str()) << endl;
cout << atof(b.c_str()) << endl;

5 截取字符串 //返回值为对象自身的引用
s.substr(pos, n) 截取s中从pos开始(包括0)的n个字符的子串,并返回
s.substr(pos) 截取s中从从pos开始(包括0)到末尾的所有字符的子串,并返回
cout << a.substr(0, 6) << endl;
cout << a.substr(1) << endl;

6 替换字符串 //返回值为对象自身的引用
s.replace(pos, n, s1) 用s1替换s中从pos开始(包括0)的n个字符的子串
cout << a.replace(0, 6, “aaaaaa”)<<endl;

7 判断字符串是否为空
string c=""; //可以赋值为空
if(c.empty())
cout<<“string is empty!”<<endl;

8 查找子字符/字符串在查找字符串中的位置
s.find(s1) 查找s中第一次出现s1的位置,并返回(包括0)
s.rfind(s1) 查找s中最后次出现s1的位置,并返回(包括0) s.find_first_of(s1) 从前往后查找s中第一次包含s1中任意字符的位置,并返回(包括0)
s.find_last_of(s1) 从后往前查找s中第一次包含s1中任意字符的位置,并返回(包括0)
s.fin_first_not_of(s1) 从前往后查找s中第一个s1中没有的字符的位置,并返回(包括0)
s.fin_last_not_of(s1) 从后往前查找s中第一个s1中没有的字符的位置,并返回(包括0)

9 字符串拼接
string f=“sbgnhfdsbdnhgfdbs”;
cout << a+f << endl; //返回值“不”为对象自身的引用
cout<<a.append(f)<<endl; //返回值为对象自身的引用

10 字符串比较
//小于 0 表示当前的字符串小
//等于 0 表示两个字符串相等
//大于 0 表示另一个字符串小
int n = a.compare(b);
n = a.compare(1, 2, b, 0, 3); //比较a的子串 (1,2) 和b的子串 (0,3)
n = a.compare(0, 2, b); // 比较a的子串 (0,2) 和 b
n = a.compare(“dsfg”);
n = a.compare(1, 2, “sdfgh”); //比较 a 的子串(1,2)和"sdfgh”
n = a.compare(1, 2, “sdfgvbn”, 1, 2); //比较 a的子串(1,2)和 “sdfgvbn” 的子串(1,2)

11 字符串交换
a.swap(b);
cout<<a<<endl;
cout<<b<<endl;

12 删除子串 //返回值为对象自身的引用
b.erase(1, 3); //删除子串,从index=1开始的后3位,包括index=1
cout<<b<<endl;
b.erase(5); //删除子串,从index=5开始的后面所有,包括index=5
cout<<b<<endl;

13 在字符串中插入字串 //返回值为对象自身的引用
b.insert(1, “sdf”); //在index=1 处插入字符串
cout<<b<<endl;
b.insert(1,2, ‘s’); //在index=1 处插入2个字符 注意是字符,字符串是不可以的
cout<<b<<endl;

14 string可以通过[]来进行索引每一个字符
cout<<b[0]<<endl;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值