zoukankan      html  css  js  c++  java
  • c++ string操作

    #include <string>
    #include <iostream>
    
    int main()
    {
        using std::cin;
        using std::cout;
        using std::endl;
        using std::string;
    
        //string初始化,
        //    使用等号(=), 执行拷贝初始化,
        //    不使用等号, 执行直接初始化.
        string s1          ; //空字符串
        string s2(s1)      ; //s2是s1的副本
        string s3("value") ; //直接初始化, s3是字面值"value"的副本
        string s4 = "value"; //拷贝初始化, 
        string s5(4, 'c')  ; //直接初始化, s5初始化为4个'c'组成的串: "ccccccccc"
    
        //string操作
        cout << "s3         : " << s3 << endl; //value, 整个字符串
        cout << "s3.empty() : " << s3.empty() << endl; //0, 判断字符串为空
        cout << "s3.size()  : " << s3.size() << endl ; //5, s3中字符数目
        cout << "s3[3]      : " << s3[3] << endl     ; //u, 返回第3字符的引用(从0开始)
        cout << "s3+s5      : " << s3+s5 << endl     ; //valuecccc, 连接字符串
        cout << "(s3==s4)   : " << (s3==s4) << endl  ; //1, 判断字符串相等
    
        //size_type: 无符号类型, 可以存放下任何string对象的大小(使用int可能溢出)
        string::size_type len0 = s4.size() ; //使用size_type存储string字符数目
        auto len1 = s5.size() ; //使用auto来推断变量类型
    
        //字面值与string对象相加, 要求两个运算对象至少有一个是string.
        string s6="hello", s7="world";
        string s8 = s6 + ", " + s7; //正确
        string s9 = s6 + ", "     ; //正确
        string s10= ", " + s7     ; //正确
        string s11= s6 + ", " + "world"; //正确, 从左向右结合
        //string s12= "hello" + ", "; //错误, 不能把两个字面值相加
        //string s13= "hello" + ", " + s7; //错误, 不能把两个字面值相加
    
        //遍历string
        cout << "loop string s6 by index: " << s6 << endl;
        for(string::size_type i=0; i<s6.size(); i++){ //使用index遍历string
            cout << "s6[" << i << "] : " << s6[i] << endl;
        }
        cout << "loop string s6 by new method: " << s6 << endl;
        for(auto c: s6){ //使用auto让编译器决定变量c的类型
            cout << c << endl;
        }
    
        //使用for改变string中的字符
        string s14 = "abcd";
        for(auto &c: s14){ //c是引用, 所以对c的修改会体现到s14中.
            c= toupper(c); //转为大写
        }
        cout << "s14 = " << s14 << endl; //s14 = ABCD
    
        return 0;
    }
    
    
  • 相关阅读:
    asp.net 框架接触(2)
    解决:C++ 中 main函数 wmain函数 _tmain函数 WinMain函数 wWInMain函数 _tWinMain函数的区别
    实现:创建/复制/移动文件API
    实现:类模板的数组类封装
    python3 解析shodan_json数据
    实现:API实现创建用户并且添加至管理员
    学习:类模板
    网展cms后台任意文件删除和sql注入
    选择排序
    实现:函数模板实现不同数据类型数组进行排序
  • 原文地址:https://www.cnblogs.com/gaiqingfeng/p/15118946.html
Copyright © 2011-2022 走看看