zoukankan      html  css  js  c++  java
  • 《c++ primer》3.2 string 小结

    1. 头文件

    #include<string>
    using std::string;

    当然,如果打了

    using namespace std;

    就不需要再打

    using std::string;

    按我理解,namespace std 就包括了string 相关的所有声明了。

    2. 声明string变量

    string s1; // 内容为空的 string
    string s2 = s1;
    string s3 = "hiya";
    string s4(10,'c'); // cccccccccc
    string s5(s4);
    string s6("hiya");

    3. 对string的操作

    os << s // os: output stream
    is >> s // is: input stream
    getline(is, s) // read a line of input
    s.empty() // returns true if empty, otherwise returns false
    s.size() // returns size of s, i.e. number of characters
    s[n] // returns the nth character, starting from 0
    s1+s2 // 两个string连缀得到一个更长的string
    s1=s2 // copy赋值
    s1==s2 // 完全相同:长度相等,字符相同
    s1!=s2 // 有不同之处
    <,<=,>,>= // ①首先判断,谁长就谁大 ②如果一样长,按字典顺序排序

    4. size_type

    为了提供一个对机器无依赖的类型,他们自定义了size_type类型,size返还的就是一个size_type类型。

    size_type类型是一个unsigned、可以是足够大的正整数的类型。

    所以,不要把 signed 类型与 size返还结果放在一起运算,避免负整数带来的问题。

    5. Range-Based for

    这好像是c++ 11的特性。

    for (declaration : expression)
        statement

    比如

    string str("some string");
    for( auto c : str)    // for every char in str
        cout<<c<<endl;

    6. 判断字符值的函数

    isalnum(c)       true if c is a letter or number
    isalpha(c)        true if c is a letter
    iscntrl(c)        true if c is a control letter
    islower(c)        true if c is a lower-case letter
    tolower(c)        if c is uppercase, returns lowercase, otherwise returns unchanged

    7. 下标

    string s("some string");
    if(!s.empty())
        s[0]=toupper(s[0]);
    cout<<s<<endl;

    下标从0开始,但要自己注意不要越界,否则结果不可预测。

  • 相关阅读:
    [剑指Offer] 10.矩形覆盖
    [剑指Offer] 9.变态跳台阶
    [剑指Offer] 8.跳台阶
    [剑指Offer] 7.斐波那契数列
    ArtifactTransferException: Failure to transfer org.apache.openejb:javaee-api:jar:5.0-1
    -Dmaven.multiModuleProjectDirectory system property is not set. Check $M2_HO 解决办法
    java中判断list是否为空的用法
    PL/SQL快速选中一行并执行
    substring的用法
    Oracle---------sql 中取值两列中值最大的一列
  • 原文地址:https://www.cnblogs.com/luyi07/p/11633335.html
Copyright © 2011-2022 走看看