C++ 字符串

C风格字符串 基本示例

#include <iostream>
#include <vector>
#include <cstring>
using namespace std; // 命名空间定义 使用C++标识符  例如:cout

int main()
{
    // 初始化变量报错:*** stack smashing detected ***: <unknown> terminated 
    // 解决方案:在拼接的时候,要尽量设置字符串大一些
    char a1 [20] {"lbw"};
    char a2 [20] {};

    // // 查看长度
    // cout << "a1 长度为: " << strlen(a1) << endl;


    // 复制 
    strcpy(a2, a1);   // a1 复制到 a2
    cout << "a2 :" << a2 << endl;   

    // 拼接
    strcat(a1, "_");  // 将空格拼接到a1后面
    strcat(a1, a2);   // 将 a2 拼接到a1后面
    cout << "拼接结果:" << a1 << endl;

    return 0;
}

char数组 查看字符串的长度

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


int main()
{   
    char a1[]{ "abcdefg"};  
    int len1;
    // 查看字符串长度
    len1 = strlen(a1);
    cout << len1 << endl;
    return 0;
}

C++ 字符串基本使用

#include <iostream>
#include <string>
using namespace std; // 命名空间定义 使用C++标识符  例如:cout

int main()
{
    string s1;                       // 空字符串
    string s2 {"hello"};             // 列表初始化
    string s3 {s2};                  // 拷贝初始化
    string s4 {"hello", 4};          // 限制字符串长度为4
    string s5 {s2, 1, 3};            // 复制s2的 1~3
    string s6 {5, 'x'};              // 5个x

    cout << "s1:" << s1 << endl;
    cout << "s2:" << s2 << endl;
    cout << "s3:" << s3 << endl;
    cout << "s4:" << s4 << endl;
    cout << "s5:" << s5 << endl;
    cout << "s6:" << s6 << endl;


    // 赋值
    string n1;
    n1 = "奥里给";
    cout << "n1: " << n1 << endl;

    string n2 {"NO NO NO"};
    n1 = n2;
    cout << "n1: " << n1 << endl;

    // 拼接
    string f1 {"C++ = "};
    string f2 {"无敌"};
    string f3;
    f3 = f1 + f2;
    cout << "f3: " << f3<< endl;

    // 获取 直接指定元素[] 或者使用 .at
    // 修改 直接指定元素等号修改即可 []=
    return 0;
}

指针访问字符串

    string str_1 = "ab12";

    string* s = &str_1;
    
    cout << *s << endl;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

默执_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值