C++中string的訪問方式


1.operator[]

函數原型:

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

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

注:如果pos等於string對象的長度,則返回'\0'字符

 

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 << '\n';
  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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM