zoukankan      html  css  js  c++  java
  • C++中的string类用法简介

    C++中的string类用法简介

    string转换为char*

    #include <iostream>
    #include<string>
    
    using namespace std;
    int main()
    {
        string str = "hello world";
        const char* pszStr = str.c_str(); //转为const char*
        cout << pszStr << endl;
        getchar();
        return 0;
    }
    

    计算string长度、string字符串比较

    string str = "hello world";
        int len = str.length();
        cout << len << endl;
        if (0 == str.compare("hello world"))
        {
            cout << "相等" << endl;
        }
    

    string对象判空

    使用empty()方法进行判断

    string str = "";
        if (str.empty())
        {
            cout << "字符串为空" << endl;
        }
    

    char*、char[]转换为string

    将char*、char[]转换为string类型时,直接进行赋值操作即可。实际上是将char*、char[]定义的字符串的首地址赋值给string对象了。

    const char* pszName = "title";
        char pszCamp[] = "测试文本";
        string strName = pszName;
        string strCamp = pszCamp;
        cout << strName << endl;
        cout << strCamp << endl;
    

    string类的find方法

    使用string类的find方法,在字符串中检索字符串是否存在。

    string str = "hello world";
        auto pos = str.find('9', 0);
        cout << pos << endl;
        if (pos == string::npos) {
            cout << "未找到" << endl;
        }
    

    string类的insert方法

    使用string类的insert方法,向字符串中插入字符(串).

    string str = "hello world";
        str.insert(4, "rg");
        cout << str << endl;
    

    int类型转为string类的方法

    使用stringstream类

    #include <iostream>
    #include<string>
    #include<sstream>
    
    using namespace std;
    int main()
    {
        int nNum1 = 123;
        stringstream ss;
        ss << nNum1;
        string str = ss.str();//转为string类型
        cout << str << endl;
    
        string str3;
        ss >> str3; //给string赋值
        cout << str3 << endl;
    
        int nNum2 = 456;
        string str4;
        str4 = to_string(nNum2); //使用to_string函数
        cout << str4 << endl;
        getchar();
        return 0;
    }
    

    删除子串

     string sl("real steel");
        sl.erase(1, 2); //删除子串(1,2)
        sl.erase(5);//删除下标为5及其后面的所有字符
    
  • 相关阅读:
    人机猜拳
    String字符串与字符(char类型)数组互相转换
    String字符串与字符(char类型)数组互相转换
    pytorch(五)超参调试过程的tensorboard可视化
    pytorch(三)建立模型(网络)
    pytorch(二)数据准备工作ETL
    pytorch(一)张量基础及通用操作
    中东冲突及圣城耶路撒冷(希伯来语为和平之城)
    五线谱基础及弹奏姿势
    相机主距与焦距
  • 原文地址:https://www.cnblogs.com/zzr-stdio/p/14292360.html
Copyright © 2011-2022 走看看