β

STL系列——string

我的个人博客 37 阅读

说到string,不得不先介绍basic_string。basic_string是各种字符类型string的泛化。

std::basic_string

template < class charT,
           class traits = char_traits<charT>,    // basic_string::traits_type
           class Alloc = allocator<charT>        // basic_string::allocator_type
           > class basic_string;
Generic string class
The basic_string is the generalization of class string for any character type (see string for a description).

Template parameters

charT
Character type.
The string is formed by a sequence of characters of this type.
This shall be a non-array POD type .
traits
Character traits class that defines essential properties of the characters used by basic_string objects (see char_traits ).
traits::char_type shall be the same as charT .
Aliased as member type basic_string::traits_type .
Alloc
Type of the allocator object used to define the storage allocation model. By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent.
Aliased as member type basic_string::allocator_type .

Note: Because the first template parameter is not aliased as any member type, charT is used throughout this reference to refer to this type.

Template instantiations

u16string String of 16-bit characters (class )

u32string String of 32-bit characters (class )

string是basic_string类模板的一个实例化,使用char类型,同时使用basic_string默认的char_trailts和allocator类型。

构造函数

default (1)        string();
copy (2)           string (const string& str);
substring (3)      string (const string& str, size_t pos, size_t len = npos);
from c-string (4)  string (const char* s);
from sequence (5)  string (const char* s, size_t n);
fill (6)           string (size_t n, char c);
range (7)          template <class InputIterator>
                   string  (InputIterator first, InputIterator last);
initializer list (8) string (initializer_list<char> il);
move (9)             string (string&& str) noexcept;

使用介绍

std::string s0 ("Initial string");

  // constructors used in the same order as described above:
  std::string s1;
  std::string s2 (s0);
  std::string s3 (s0, 8, 3);                       // from pos = 8, len = 3
  std::string s4 ("A character sequence", 6);      // first n characters pointed by s
  std::string s5 ("Another character sequence");   // pointed by s
  std::string s6a (10, 'x');                   // Fills the string with n consecutive copies of character c.
  std::string s6b (10, 42);      // 42 is the ASCII code for '*'
  std::string s7 (s0.begin(), s0.begin()+7);

赋值运算符 std:: string ::operator=

string (1)           string& operator= (const string& str);
c-string (2)         string& operator= (const char* s);
character (3)        string& operator= (char c);
initializer list (4) string& operator= (initializer_list<char> il);
move (5)             string& operator= (string&& str) noexcept;

使用介绍

str1 = "Test string: ";   // c-string
str2 = 'x';               // single character
str3 = str1 + str2;       // string

迭代器

begin()、end()       an iterator or a const_iterator(if string object is const)
rbegin()、rend()     a reverse_iterator or a const_reverse_iterator
cbegin()、cend()     const_iterator
crbegin()、crend()

Capacity

size_t size() const noexcept;
size_t length() const noexcept;
// size 和 length相同,返回string实际字节数,不一定和capacity不同

void resize (size_t n);
void resize (size_t n, char c);     // 调整string的长度到length,如果n < length截短;如果n > length,用字符c进行填充,c没有指定,填充空字符

size_t max_size() const noexcept;  // string能够到达的最大长度,与操作系统或者库的实现有关
size_t capacity() const noexcept;  // 当前给string分配的空间,当前空间用完时,自动扩展,理论最大长度为max_size();任意时刻都能修改;可以被reserve()显式地修改
void reserve (size_t n = 0);       //如果n>capacity(),增加capacity()到n;其他情形不强制约定;reserver不改变string内容和length

void clear() noexcept;              // 清空string中内容
bool empty() const noexcept;        // 判断string内容是否为空

void shrink_to_fit();                // C++11, 减少capacity到string的size;不是强制的,具体试容器实现;不改变string内容和length

元素访问

char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;
// 返回pos位置指向字符的引用,如果pos == length,返回空字符引用 如果string是常量,返回 const char&,否则返回char&

char& at (size_t pos);
const char& at (size_t pos) const;  // 类似于[],不过这里可以检测pos是否小于length,否则抛出异常out_of_range()

char& back();
const char& back() const;  // 返回string中最后一个字符的引用,string不能为空,否则抛出异常

 char& front();
const char& front() const;  // 返回string中第一个字符的引用,string不能为空,否则抛出异常

Modifiers

// std::string::operator+=
// Append to string
// return value: *this
string (1)           string& operator+= (const string& str);
c-string (2)         string& operator+= (const char* s);
character (3)        string& operator+= (char c);
initializer list (4) string& operator+= (initializer_list<char> il);
// Extends the string by appending additional characters at the end of its current value
// std::string::append
// Append to string. Extends the string by appending additional characters at the end of its current value
string (1)        string& append (const string& str);
substring (2)     string& append (const string& str, size_t subpos, size_t sublen = npos);
c-string (3)      string& append (const char* s);
buffer (4)        string& append (const char* s, size_t n);
fill (5)          string& append (size_t n, char c);
range (6)         template <class InputIterator>
                      string& append (InputIterator first, InputIterator last);
initializer list(7) string& append (initializer_list<char> il);
void push_back (char c);
// Appends character c to the end of the string, increasing its length by one.

// string::push_back
#include <iostream>
#include <fstream>
#include <string>

int main ()
{
  std::string str;
  std::ifstream file ("test.txt",std::ios::in);
  if (file) {
    while (!file.eof()) str.push_back(file.get());
  }
  std::cout << str << '\n';
  return 0;
}
// return value: *this
string (1)        string& assign (const string& str);
substring (2)     string& assign (const string& str, size_t subpos, size_t sublen = npos);
c-string (3       string& assign (const char* s);
buffer (4)        string& assign (const char* s, size_t n);
fill (5)          string& assign (size_t n, char c);
range (6)         template <class InputIterator>
                     string& assign (InputIterator first, InputIterator last);
initializer list(7) string& assign (initializer_list<char> il);
move (8)            string& assign (string&& str) noexcept;
// Inserts additional characters into the string right before the character indicated by pos (or p):
// return value
// The signatures returning a reference to string, return *this.
// Those returning an iterator, return an iterator pointing to the first character inserted.

string (1)          string& insert (size_t pos, const string& str);
substring (2)       string& insert (size_t pos, const string& str, size_t subpos, size_t sublen = npos);
c-string (3)        string& insert (size_t pos, const char* s);
buffer (4)          string& insert (size_t pos, const char* s, size_t n);
fill (5)            string& insert (size_t pos,   size_t n, char c);
                    iterator insert (const_iterator p, size_t n, char c);
single character (6) iterator insert (const_iterator p, char c);
range (7)            template <class InputIterator>
                         iterator insert (iterator p, InputIterator first, InputIterator last);
initializer list (8)  string& insert (const_iterator p, initializer_list<char> il);
// Erase characters from string
// Erases part of the string, reducing its length:
// return value:
// The sequence version (1) returns *this.
// The others return an iterator referring to the character that now occupies the position of the first character erased, or string::end if no such character exists.
sequence (1)  string& erase (size_t pos = 0, size_t len = npos);
character (2) iterator erase (const_iterator p);
range (3)     iterator erase (const_iterator first, const_iterator last);
string (1)    string& replace (size_t pos,        size_t len,        const string& str);
              string& replace (const_iterator i1, const_iterator i2, const string& str);
substring (2) string& replace (size_t pos,        size_t len,        const string& str,
                 size_t subpos, size_t sublen);
c-string (3)  string& replace (size_t pos,        size_t len,        const char* s);
              string& replace (const_iterator i1, const_iterator i2, const char* s);
buffer (4)    string& replace (size_t pos,        size_t len,        const char* s, size_t n);
              string& replace (const_iterator i1, const_iterator i2, const char* s, size_t n);
fill (5)      string& replace (size_t pos,        size_t len,        size_t n, char c);
              string& replace (const_iterator i1, const_iterator i2, size_t n, char c);
range (6)     template <class InputIterator>
                   string& replace (const_iterator i1, const_iterator i2,
                   InputIterator first, InputIterator last);
initializer list (7) string& replace (const_iterator i1, const_iterator i2, initializer_list<char> il);
// Swap string values
// Exchanges the content of the container by the content of str, which is another string object. Lengths may differ.
// After the call to this member function, the value of this object is the value str had before the call, and the value of str is the value this object had before the call.

void swap (string& str);
// Delete last character
// Erases the last character of the string, effectively reducing its length by one.

void pop_back();

String operations

const char* c_str() const noexcept;     返回C-string类型的字符串,和string::data返回同样的值

allocator_type get_allocator() const noexcept;         Get allocator. Returns a copy of the allocator object associated with the string .

size_t copy (char* s, size_t len, size_t pos = 0) const;

copy将string从pos位置起,长度为len的子字符串,拷贝到s中;返回拷贝的字符数;注意这里不会自动在拷贝的内容后面添加结束符。

// std::string::find
// Searches the string for the first occurrence of the sequence specified by its argument
// return value:
//The position of the first character of the first match.
//If no matches were found, the function returns string::npos.

string (1)    size_t find (const string& str, size_t pos = 0) const noexcept;
c-string (2)  size_t find (const char* s, size_t pos = 0) const;
buffer (3)    size_t find (const char* s, size_t pos, size_type n) const;
character (4) size_t find (char c, size_t pos = 0) const noexcept;
// Searches the string for the first character that matches any of the characters specified in its arguments.

string (1)     size_t find_first_of (const string& str, size_t pos = 0) const noexcept;
c-string (2)   size_t find_first_of (const char* s, size_t pos = 0) const;
buffer (3)     size_t find_first_of (const char* s, size_t pos, size_t n) const;
character (4)  size_t find_first_of (char c, size_t pos = 0) const noexcept;

rfind() 查找最后一个匹配的位置。 find_first_of() 只需要匹配指定制定字符或者字符串中任意一个字符就行,而find()必须匹配整个给定的内容。

与find_first_of( )相反,find_last_of( ) 找最后一个匹配。当pos指定时,只找pos之前的,pos默认为string::npos

find_first_not_of寻找第一个不与指定字符或者字符串中任一字符匹配的位置。  find_last_not_of( ) 与find_last_of( )类似。

string substr (size_t pos = 0, size_t len = npos) const;

string (1)     int compare (const string& str) const noexcept;
substrings (2) int compare (size_t pos, size_t len, const string& str) const;
               int compare (size_t pos, size_t len, const string& str,
                   size_t subpos, size_t sublen = npos) const;
c-string (3)   int compare (const char* s) const;
               int compare (size_t pos, size_t len, const char* s) const;
buffer (4)     int compare (size_t pos, size_t len, const char* s, size_t n) const;

compare返回值0. >0, <0

string::npos是一个静态成员常量值,值定义为-1,是无符号类型size_t最大的可能的代表值。

非成员函数重载

void swap (string& x, string& y);
void swap (string& x, string& y);

string (1)     string operator+ (const string& lhs, const string& rhs);
c-string (2)   string operator+ (const string& lhs, const char*   rhs);
               string operator+ (const char*   lhs, const string& rhs);
character (3)  string operator+ (const string& lhs, char          rhs);
               string operator+ (char          lhs, const string& rhs);

istream& operator>> (istream& is, string& str);   // 从输入流中提取字符串存储到string中,使用空格作为分隔符

ostream& operator<< (ostream& os, const string& str);

istream& getline (istream&  is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);

istream& getline (istream&  is, string& str);
istream& getline (istream&& is, string& str);
//Get line from stream into string
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).
The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.
If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.
作者:我的个人博客
记录成长途中的点滴总结
原文地址:STL系列——string, 感谢原作者分享。

发表评论