浅谈c++string类用法

借鉴于:
https://blog.csdn.net/liitdar/article/details/80498634

1.string转换为char*

使用c_str()方法或data()方法,这两个方法在c++11标准中用法相同

//string 转换为char*
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string strOutput = "Hello World";
    //cout 可以直接输出string类的对象的内容
    cout << "[cout] strOutput is:"
        << strOutput << endl;
    //string 转换为char*
    const char *pszOutput = strOutput.c_str();
    //因为string对象一旦初始化就不可变
    //所以要加const
    //c_str()方法和data()方法在c++11版本中一样
    printf("[printf] strOutput is:%s\n"
           , pszOutput);
    //printf()函数不能直接打印string类的
    //对象的内容,可以通过将string转换为
    //char*类型,在使用printf()函数打印
    return 0;
}

2.计算string长度和比较string字符串

#include <iostream>
#include <string>

#define HELLOSTR "Hello, World!"

using namespace std;

int main()
{
    string strOutput = "Hello, World!";
    
    int nLen = strOutput.length();
    // 计算字符串长度的方法
    cout << "The length of strOutput is:" 
        << nLen << endl;
    if (strOutput.compare(HELLOSTR) == 0) {
        // 比较字符串的方法
        cout << "strOutput equal with macro HELLOSTR"
            << endl;
    }

    return 0;
}

3.char* char[]转换为string

#include <iostream>
#include <string>

using namespace std;

int main()
{
    const char *pszName = "liitdar";
    char pszCamp[] = "alliance";

    string strName;
    string strCamp;

    strName = pszName;
    strCamp = pszCamp;
    //将char* char[]转换为string类型时,直接
    //进行赋值操作,将char* char[]的变量赋值
    //给string对象即可.
    //这里的赋值实际上是将字符串的首地址赋值
    //给string对象了
    cout << strName << endl;
    cout << strCamp << endl;
    return 0;
}

4.string类的find方法

//使用string类的find方法, 在字符串中检索
//子字符串是否存在.
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string strOutput = "|0|1|2|";
    string strObj = "|1|";
    
    size_t nLoc = strOutput.find(strObj);
    // find方法的返回类型为size_t,
    // 如果检索到子串,返回子串在字符串
    // 中的位置,如果没有检索到,返回
    // string::npos
    if (nLoc != string::npos) {
        cout << nLoc << endl;
    }

    return 0;
}

5.string类的insert方法

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string strDemo = "I am";

    strDemo.insert(2, " good.");
    //使用string类的insert方法,向字符串
    //前面插入字符(串)
    cout << "strDemo is:" << strDemo << endl;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值