c++入门string标准库操作

string对象的定义和初始化

在这里插入图片描述
代码示例:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string s1 = "a";
    cout << "s1 = " << s1 << endl; //s1 = a

    string s2(s1); //将 s2 初始化为 s1 的一个副本	
    cout << "s2 = " << s2 << endl; // s2 = a

    string s3("an"); //将 s3 初始化为 "mike"
    cout << "s3 = " << s3 << endl; // s3 = an

    string s4(6, 'b'); // s4 的值为 6 个 'b'	
    cout << "s4 = " << s4 << endl; 
    return 0;
}
常用操作

在这里插入图片描述
代码:

#include <iostream>
#include <string>
using namespace std;

int main(){
    string s1 = "an";

    // 如果s1为空串,则返回true,否则返回false	
    if( true == s1.empty() ){
       cout << "s1 is empty\n";
    }else{
       cout << "s1 is no empty\n";
    }

    // 字符串的大小, s1.size()等价于s1.length()
    cout << "len = " << s1.size() << endl;

    //返回 s1 最大容量	
    cout << "max_size = " << s1.max_size() << endl;
    //取出每一个字符
    for(int i = 0; i < s1.size(); i++){
    //s1[i]等价于s1.at(i)	
    	cout << i << " = " << s1[i] << endl;
    }
    
    string s2 = " dog";	
    cout << "s1 + s2 = " << s1+s2 << endl;

    const char *data = s2.data();
    cout << "data = " << data << endl;

    const char *buf = "hello";
    //string my_str = string(buf);
    string my_str = buf;
    cout << "my_str = " << my_str << endl;

    //s1和s2字符串交换
    s1 = "me";	
    s2 = "love";
    s1.swap(s2);
    cout << "s1 = " << s1 << ", s2 = " << s2 << endl;
    
    s1.clear();
    s1 = "meloveyou";
    //取出 s1 从 2 开始后的 3个字符,位置从0开始
    s2 = s1.substr(2, 3);
    cout << "s2 = " << s2 << endl;
    
    s1 = "me";	//s1 从 4 开始(位置从0开始),插入"love"字符串
    s2 = s1.insert(4, "love");
    cout << "s2 = " << s2 << endl;

     s1="melove";	//删除s1从3开始的2个字符,然后在3位置处插入"an"	
     s2 = s1.replace(4, 3, "an");
     return 0;
}
迭代器操作

在这里插入图片描述

#include <iostream>
#include <string>
using namespace std;
int main(){
    string s="hellome"; //初始化为"hellome"
    
    //通过迭代器把所有字符元素的值打印出来
    string::const_iterator t;
    
    for( t=s.begin(); t!=s.end(); t++){	
    	cout<< *t << ", ";
    }
    cout << endl;

    string::iterator it;
    //通过迭代器给所有字符元素赋值为'b'
    for( it=s.begin(); it!=s.end(); it++){
    	*it = 'b';
    }
     cout << endl;

    s = "hellome";
    it = s.begin(); //返回指string最开始位置元素的指针(迭代器)	//删除指针it+1指向位置的元素,返回指向下一个元素位置的指针(迭代器)	
    s.erase(it+1);

    for( it=s.begin(); it!=s.end(); it++){
    	cout<< *it << ", ";
    }
    cout << endl;

    s = "aaaaaa";
    it = s.begin();
    //在位置it后插入3个'b'	
    s.insert(it, 3, 'b');

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值