C++字符串处理函数

在C++中,字符串处理函数是通过标准库中的string类提供的成员函数来实现的。以下是一些常用的C++字符串处理函数:

获取字符串长度

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

int main() {
    string str = "Hello, World!";

    // 获取字符串长度
    cout << "字符串的长度为: " << str.length() << endl;

    return 0;
}

字符串连接

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

int main() {
    string str1 = "Hello, ";
    string str2 = "World!";

    // 字符串连接
    string result = str1 + str2;
    cout << result << endl;

    return 0;
}

截取子串

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

int main() {
    string str = "Hello, World!";

    // 截取子串
    string sub = str.substr(7, 5); // 从第7个字符开始,截取5个字符
    cout << sub << endl;

    return 0;
}

查找子串

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

int main() {
    string str = "Hello, World!";

    // 查找子串
    size_t found = str.find("World");
    if (found != string::npos) {
        cout << "子串\"World\"在位置 " << found << " 处被找到" << endl;
    } else {
        cout << "未找到子串" << endl;
    }

    return 0;
}

C++的string类还提供了其他的成员函数来进行字符串处理,具体的函数可以根据需求选择使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值