zoukankan      html  css  js  c++  java
  • 3.1 String容器

    补充:

    #include<string>    头文件中其实还包含了一些函数很有用,比如to_string()函数,函数名称在std中,函数能够将各种类型的数字转换成字符串!

    #include<cstring>  是C语言的头文件,里头包含了一些常用的函数,比如atoi和stoi,二者都能将数字字符串转换成整数,stoi更好用一些。https://www.cnblogs.com/bluestorm/p/3168719.html

     

        string s1;
    
        const char* str = "hello world";
        string s2(str);
    
        string s3(s2);
    
        string s4(10, 'a');

    C语言字符串的本质是一个指针,字符指针

    构造函数是初始化操作

        string str1;
        str1 = "hello world";
    
        string str2;
        str2 = str1;
    
        string str3;
        str3 = 'a';
    
        string str4;
        str4.assign("hello C++");
    
        string str5;
        str5.assign("hello C++", 5);// 把字符串的前5个字符拷贝
    
        string str6;
        str6.assign(str5);
    
        string str7;
        str7.assign(10, 'w'); // 10个w

    最后一个pos从0开始

    append最后一个方式非常灵活

    #include<iostream>
    #include<vector>
    #include<string>
    using namespace std;
    
    // string字符串查找和替换
    
    // 查找
    void test01()
    {
        string str1 = "abcdefg";
        int pos = str1.find("de"); // 从0开始查
        if (pos == -10)
            cout << "not find" << endl;
        else
            cout << pos << endl; // 3
        // 如果查找没有,返回-1
    
        // rfind从右往左查找,find从左往右查找
        pos = str1.rfind("de");
    }
    
    void test02()
    {
        string str1 = "abcdefg";
        str1.replace(1, 3, "1111"); // 从1号位置起,3个连续字符替换成1111
        cout << str1 << endl;
    }
    int main()
    {    
        test02();
        return 0;
    }

     

    if (str1.compare(str2))

    通常比较大小没有意义,最大意义是比较二者是否相等。

    1.内部重载[]

    2.at的方式

    两种方式都可以读和写

    #include<iostream>
    #include<vector>
    #include<string>
    using namespace std;
    
    // string字符串插入和删除
    
    // 查找
    void test01()
    {
        string str = "hello";
    
        //插入
        str.insert(1, "111");
        //删除
        str.erase(1, 3);
    }
    
    int main()
    {    
        test01();
        return 0;
    }

    插入和删除起始下标都从0开始

    截取里面的一小串

    pos:位置

    npos:个数

    #include<iostream>
    #include<vector>
    #include<string>
    using namespace std;
    
    // string字符串子串
    
    // 查找
    void test01()
    {
        string str = "hello";
        string subStr = str.substr(1, 3); // 从1开始截3个
        cout << subStr << endl;
    
        
    }
    
    void test02()
    {
        string email = "hello@sina.com";
        // 从地址中获取用户名信息
        int pos = email.find("@");
        string uerName = email.substr(0, pos);
        cout << uerName << endl;
    }
    
    int main()
    {    
        test02();
        return 0;
    }
  • 相关阅读:
    lnmp环境搭建
    Git常用命令
    博客园写随笔环境搭建
    Win常用软件
    Docker环境搭建
    ESP-8266 RTOS 环境搭建
    查看Linux信息
    博客园markdown语法
    Java后台技术(TDDL)
    Java后台技术(Dubbo入门)
  • 原文地址:https://www.cnblogs.com/masbay/p/14294385.html
Copyright © 2011-2022 走看看