C++字符串(二)

C++中string类型字符串代码示例

//string 字符串使用示例
//string.cpp
#include <iostream>
#include <cstring>
using namespace std;
int main(void){
    string s;//空字符串
    cout<< s <<endl;//结果是啥也没有
    string s1 = "hello";//定义并同时初始化
    cout<< s1 <<endl;//结果:hello
    //拷贝
    string s2;
    /*该拷贝过程形式简单,也比较安全,不用担心内存问题。
    s1占用6个字符空间,s2仅仅是定义了,且是空字符,能够
    放下s1吗?其实不用担心,因为string类型是在堆区开辟
    空间维护字符串的,它将过程都封装起来了,若拷贝过程
    中发现s2的内存不够用,他会完成动态的内存分配*/
    s2 = s1;
    cout<< s2 <<endl;//hello
    
    //连接
    string s3 = s1 + s2;
    cout << s3 <<endl;//hellohello
    //也可以和常量字符串连接
    s3 = s1 + "world";
    cout<< s3 <<endl;//hello world
    //连接也可以用“+=”
    s1  += "world";//s1=s1+"world";
    cout<< s1 <<endl;//hello world
    
    //比较
    /*比较两字符串使用的较多的是判断两个字符串是否相等,
    返回值是个逻辑值,若是真结果为1,若是假结果为0*/
    cout<< (s1 == s2)<<endl;//0
    cout<< (s1 != s2)<< endl;//1
    
    //随机访问
    /*随机访问是获取任意一个想要的字符*/
    s1[0] = 'H';
    s1[6] = 'W';
    cout<< s1 <<endl;//Hello World
    
    //获取字符串长度
    /*获取字符串长度的函数是string的成员函数,可以
    将string理解为结构体类型,里面包含和字符串相关
    的成员函数。在求字符串长度时的结果是不包含字符
    串结束标志“\n”的。以下两个成员函数等价,一般使
    用第一个,由于字母少写起来简单。*/
    cout<< s1.size() <<endl;//11
    cout<<s1.length() <<endl;//11
    
    //获取C风格的字符串
    /*strlen()的参数为char* 类型的,使用成员函数c_str()
    转换后再使用*/
    cout<< strlen(s1.c_str())<< endl;//11
        
    //交换
    string s4= "hello";
    string s5="world";
    swap(s4,s5);
    cout<< s4 <<endl;//world
    cout<< s5 <<endl;//hello
    
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值