【C++编程】字符串 string 容器基本操作

构造 string 的四种方法

#include<iostream>
#include<string.h>
		
using namespace std;
		
		 
int main()
{
   // 1. 同时展示常用的赋值操作
   string s1;
   s1 = "hello world";             // 赋值 hello world
   s1.assign("hello world");	   // 赋值 hello world
   s1.assign("hello world", 2);    // 赋值 he
   s1.assign(10, "a",);            // 赋值 aaaaaaaaaa
   // 2.
   const char *str = "hello world";
   string s2(str);      // hello world
   // 3.
   string s3(s1);       // hello world
   // 4.
   string s4(10, 'a');  // "aaaaaaaaaa"
		
   return 0; 
}

字符串拼接、截取、删除、插入:+=appendsubstreraseinsert

// 拼接
string s1 = "a";	    		// "a"          
s1 += "bc";             		// "abc"
s1.append("def");       		// "abcdef"
s1.append("ghij", 3);   		// "abcdefghi"

// 截取
string s2 = s1.substr(1, 2);	// “bc”, 从idx-1开始的2个
// 删除
string s2 = s1.erase(1, 2);		// “adefghi”,删除 “bc”

// 插入
string s3 = s1.insert(1, "bc");	// "abcdefghi", 从idx-1开始插入 "bc"

字符串长度获取:lengthsize

string s1 = "abcdef";
cout << s1.length() << endl; 	// 6
cout << s1.size() << endl; 		// 6

字符串查找与替换:findreplace

string s1 = "abcdef";         
cout << s1.find("de") << endl;  // 3 -> 找到,位于 index 3  
cout << s1.replace(1, 2, "1111") << endl;  // a1111def  ->  bc(从idx-1开始的2个) 替换为 1111

字符串排序:sort

// 需要头文件 #include <algorithm>
string s1 = "acbfde";
sort(s1.begin(), s1.end());  // abcdef

【博客参考链接】
【黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难】

  • 22
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值