C++ string(初始化和部分函数的使用)

本文详细介绍了使用C++标准库中的string类进行字符串初始化及各种常用操作的方法,包括字符串长度获取、字符访问、字符串清空等,并通过示例代码展示了这些功能的具体应用。

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

#include<string>
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
using namespace std;

int main()
{
    //string 初始化
    string s1 = "ywb";
    string s2(s1);
    string s3 = s2;
    string s4("yangwen");
    string s5(10, 'c');
    cout << s1 << " " << s2 << " " << s3 << " " << s4 << " " << s5 << endl;


    //string 一部分函数的使用
    string str("yangwenbin");
    int length = str.length();//求取字符串长度
    int length1 = str.size(); //求取字符串长度
    cout << length << " " << length1 << endl;
    for (int i = 0; i < length1; i++)
    {
        cout << str.at(i) << " " ;  //返回字符串第i个位置的字符
    }
    cout << endl;
    cout << *str.begin() << endl;   //返回字符串的首字符
    cout << *(str.end() - 1) << endl;; //返回字符串的尾元素
    if (!str.empty())  //判断字符串是否为空
    {
        cout << "i am not empty" << endl;;
    }
    str.resize(length + 10, 'a'); //重新分配空间,将多余的十个空间分配a
    cout << str << endl;;
    str.clear(); //清除字符串

    if (str.empty())  //判断字符串是否为空
    {
        cout << "i am empty" << endl;;
    }
    str.append("ywb");
    cout << str << endl;
    str.append(" hell0");//append 在string后插入字符串
    cout << str;
    system("pause");
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值