zoukankan      html  css  js  c++  java
  • C++中string的访问方式

    1.operator[]

    函数原型:

    char& operator[] (size_t pos);
    const char& operator[] (size_t pos) const;

    函数作用:返回pos位置的字符的引用

    注:如果pos等于string对象的长度,则返回''字符

    2.at()

    函数原型:

    char& at (size_t pos);
    const char& at (size_t pos) const;

    函数作用:返回string对象pos位置的字符

    注:该函数自动检查pos位置是否是有效的位置(自动判断是否越界)

    3.front()

    函数原型:

    char& front();
    const char& front() const;

    作用:返回字符串首字符的引用

    不像迭代器begin,该函数只返回引用,且空字符串不会调用该函数

    Returns a reference to the first character of the string.
    Unlike member string::begin, which returns an iterator to this same character, this function returns a direct reference.
    This function shall not be called on empty strings.

    例子:

    // string::front
    #include <iostream>
    #include <string>
    
    int main ()
    {
      std::string str ("test string");
      str.front() = 'T';
      std::cout << str << '
    ';
      return 0;
    }
    输出:Test string

    4.back()

    函数原型:

    char& back();
    const char& back() const;

    函数作用:返回string对象最后一个字符的引用

    注:空字符串不会调用该函数

    Returns a reference to the last character of the string.
    This function shall not be called on empty strings.

  • 相关阅读:
    dubbo服务provider方打印警告日志,getDeserializer
    [学习]sentinel中的DatatSource(一) ReadableDataSource
    ppt字体
    dubbo异常filter
    术语
    [转]五步git操作搞定Github中fork的项目与原作者同步
    markdown学习资料
    springboot properties
    aop备忘
    git技巧
  • 原文地址:https://www.cnblogs.com/jainszhang/p/10692965.html
Copyright © 2011-2022 走看看