算法c++之stl---string的详细使用

本文通过实例演示了C++中标准库字符串的各种操作方法,包括获取、打印字符串及其长度,提取子串,调整字符串大小,替换内容,以及查找特定文本的位置等。适合初学者和需要复习字符串操作的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<bits/stdc++.h> 
using namespace std;


int main(){
	//获取一行字符串
	string s="What we have here is a failure to communicate";
//	getline(cin,s);
	//打印 
	cout<<s[0]<<endl; 
	//获取字符串的长度
	cout<<"字符串的长度:"<<s.length()<<endl; 
	string sub = s.substr(21);
    cout << "The original string is " << s << endl;
    cout << "The substring is " << sub << endl;
    
    //size()函数返回字符串中现在拥有的字符数。
	cout<<s.size(); 
	//resize()函数改变本字符串的大小到num, 新空间的内容不确定。也可以指定用ch填充。
	s.resize(100,'x'); 
	cout<<s<<endl; 
	//replace替换
	s = "They say he carved it himself...from a BIGGER spoon";
    string s2 = "find your soul-mate, Homer.";

    s.replace( 32, s2.length(), s2 );

    cout << s << endl;
    //string的copy 
    char* c=new char[10];
	strcpy(c,s.c_str());
	cout<<c; 
	//添加文本
	s.append(10,'*');
	cout<<s<<endl; 
 	//查找say的位置 
 	unsigned int loc = s.find_last_of ( "say", s.length() );
 	if( loc != string::npos )
      cout << "Found say at " << loc << endl;
    else
      cout << "Didn't find say" << endl;

	//插入insert方法
	//begin和end方法 
	return 0; 
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值