构造函数

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 buffer (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;

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// string constructor
#include <iostream>
#include <string>

int main ()
{
  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);
  std::string s4 ("A character sequence");
  std::string s5 ("Another character sequence", 12);
  std::string s6a (10, 'x');
  std::string s6b (10, 42);      // 42 is the ASCII code for '*'
  std::string s7 (s0.begin(), s0.begin()+7);

  std::cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3;
  std::cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6a: " << s6a;
  std::cout << "\ns6b: " << s6b << "\ns7: " << s7 << '\n';
  return 0;
}

迭代器

容量

length和size函数

返回字符串的长度,以字节为单位.

这是符合字符串内容的实际字节数,这不一定等于其存储容量。

注意串对象处理字节,而不知道可能最终用于编码其包含的字符的编码。因此,返回的值可能与多字节或可变长度字符(如UTF-8)序列中的编码字符的实际数量不符。

string :: size和string :: length都是同义词,并返回完全相同的值

resize函数

调整string的length值.

size_t 是一个无符号整型类型(与成员类型相同) 字符串:: SIZE_TYPE)。

函数原型:

1
2
void resizesize_t n;
void resizesize_t nchar c;

将字符串的length调整为n个字符的长度。 如果n小于当前字符串长度,则将当前值缩短为其第n个字符,删除超出第n个字符的字符。 如果n大于当前字符串长度,则通过根据需要插入许多字符来扩展当前内容,以达到大小n。如果指定了c,新元素将被初始化为c的副本,否则它们是值初始化的字符(空字符)。

capacity函数

返回当前为字符串分配的存储空间的大小,以字节为单位。

该容量不一定等于字符串长度。它可以相等或更大,当添加新字符到字符串时,允许对象优化其操作的额外空间。

请注意,该容量并不是对字符串长度的限制。当这个容量耗尽并且需要更多时,它被对象自动扩展(重新分配它的存储空间)。字符串长度的理论限制由成员max_size给出。

每当对象被修改时,字符串的容量就可以改变,即使这种修改意味着尺寸减小或容量没有用尽(这与向量容器中的容量保证相反)。

capacity存在最小值,在GCC中即使size值为1,capacity的值仍为15,且无法改变.

reserve函数

调整string的capacity值.

请求将字符串容量调整为计划的大小更改为最多n个字符的长度。 如果n大于当前字符串容量,该函数将使容器将其容量增加到n个字符(或更大)。

该请求是非绑定的,容器可以自由地优化,留下capacity大于其size的字符串。

他的功能对字符串的length没有影响,如果reserve将string的capacity缩小到低于size值,那么capacity值将自动扩展到size值大小.

max_size函数

返回字符串可达到的最大长度,这是由于已知的系统或库实现限制,字符串可以达到的最大潜在长度,但是该对象不能保证能够达到该长度:在达到该长度之前的任何时间点仍然可能无法分配存储。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  std::cout << "size: " << str.size() << "\n";
  std::cout << "length: " << str.length() << "\n";
  std::cout << "capacity: " << str.capacity() << "\n";
  std::cout << "max_size: " << str.max_size() << "\n";
  return 0;
}

返回值如下:

1
2
3
4
size: 11
length: 11
capacity: 15
max_size: 9223372036854775807

shrink_to_fit函数

请求字符串减小capacity至size。

该请求是非绑定的,容器可以自由地优化,会出现capacity大于其size的情况。

示例如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <iostream>
#include <string>

int main ()
{
  std::string str (100,'x');
  std::cout << "1. capacity of str: " << str.capacity() << '\n';

  str.resize(20);
  std::cout << "2. capacity of str: " << str.capacity() << '\n';

  str.shrink_to_fit();
  std::cout << "3. capacity of str: " << str.capacity() << '\n';

  return 0;
}

返回结果:

1
2
3
1. capacity of str: 100
2. capacity of str: 100
3. capacity of str: 20

实现原理

使用"swap技巧"除去多余的容量

做法:

vector<Contestant>(Contestants).swap(Contestants)

表达式vector(Contestants)创建一个临时的向量,它是contestants的拷贝:这是由vector的拷贝构造函数来完成的.然而,vector的拷贝构造函数只为所拷贝的元素分配所需要的内存,所以这个临时向量没有多余的容量.然后我们把临时向量中的数据和contestant中的数据做swap操作,在这之后,contestant具有了被去除之后的容量,即原先临时变量的容量,而临时变量的容量则变成了原先contestants臃肿的容量,而临时变量的容量则变成了原先contestants臃肿的容量.到这时,临时向量被析构,从而释放了先前为contestant所占据的内存.

同样的技巧对string也适用.

string(s).swap(s);

这一技术并不保证一定能除去多余的容量.这取决于STL的实现.STL实现者如果愿意的话,可以自由地为vector和string保留多余的容量.

元素访问

注意:元素访问函数的返回值都是字符的引用,而不是迭代器

at函数

返回对字符串中位置pos处的字符的引用。

该函数自动检查pos是字符串中字符的有效位置(即pos是否小于字符串长度),如果不是,则抛出out_of_range异常。

如果字符串对象是const-qualified,则该函数返回一个const char&。否则,它返回一个char&。

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  for (unsigned i=0; i<str.length(); ++i)
  {
    std::cout << str.at(i);
  }
  return 0;
}

back和front函数

back函数返回对字符串最后一个字符的引用。 空字符串不得调用此函数。

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <iostream>
#include <string>

int main ()
{
  std::string str ("hello world.");
  str.back() = '!';
  std::cout << str << '\n';
  return 0;
}

front函数同理.空字符串不得调用此函数

修改

operator+=

  1. string (1)

     string& operator+= (const string& str);
    

    str:一个字符串对象,其值被复制到最后。

  2. c-string (2)

     string& operator+= (const char* s);
    

    s:指向以null结尾的字符序列。

    该序列被复制在字符串的末尾。

  3. character (3)

     string& operator+= (char c);
    

    c:一个字符,附加到字符串的当前值。

  4. initializer list (4)

     string& operator+= (initializer_list<char> il);
    

    il:这些对象由初始化列表声明符自动构建。

    字符以相同的顺序附加到字符串中。

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include <iostream>
#include <string>

int main ()
{
  std::string name ("John");
  std::string family ("Smith");
  name += " K. ";         // c-string
  name += family;         // string
  name += '\n';           // character

  std::cout << name;
  return 0;
}

append函数

通过在其当前值的末尾附加附加字符来扩展字符串:

  1. string (1)

     string& append (const string& str);
    

    附加一个str的副本。

  2. substring (2)

     string& append (const string& str, size_t subpos, size_t sublen);
    

    附加一个str的子串的副本。子字符串是从subpos开始的长度为sublen的字符串(如果str太短或如果sublen是string :: npos,则子串到str.end)

  3. c-string (3)

     string& append (const char* s);
    

    附加由s指向的以null结尾的字符序列(C-string)形成的字符串的副本。

  4. buffer (4)

     string& append (const char* s, size_t n);
    

    在s指向的字符数组中附加前n个字符的副本。

  5. fill (5)

     string& append (size_t n, char c);
    

    附加n个连续的字符c。

  6. range (6)

     template <class InputIterator>
     	string& append (InputIterator first, InputIterator last);
    

    以相同的顺序追加range[first,last]中的字符序列的副本。

  7. initializer list(7)

     string& append (initializer_list<char> il);
    

    以相同的顺序在il附加每个字符的副本。

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

int main ()
{
  std::string str;
  std::string str2="Writing ";
  std::string str3="print 10 and then 5 more";

  // used in the same order as described above:
  str.append(str2);                       // "Writing "
  str.append(str3,6,3);                   // "10 "
  str.append("dots are cool",5);          // "dots "
  str.append("here: ");                   // "here: "
  str.append(10u,'.');                    // ".........."
  str.append(str3.begin()+8,str3.end());  // " and then 5 more"
  str.append<int>(5,0x2E);                // "....."

  std::cout << str << '\n';
  return 0;
}

push_back函数

void push_back (char c);

将字符c附加到字符串的末尾,将其长度增加1。

assign函数

为字符串分配一个新值,替换其当前string所有内容。

  1. string (1)

     string& assign (const string& str);
    
  2. substring (2)

     string& assign (const string& str, size_t subpos, size_t sublen);
    
  3. c-string (3)

     string& assign (const char* s);
    
  4. buffer (4)

     string& assign (const char* s, size_t n);
    
  5. fill (5)

     string& assign (size_t n, char c);
    
  6. range (6)

     template <class InputIterator>
     	string& assign (InputIterator first, InputIterator last);
    
  7. initializer list(7)

     string& assign (initializer_list<char> il);
    
  8. move (8)

     string& assign (string&& str) noexcept;
    

    获取str的内容。 str保留在未指定但有效的状态。

举例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <string>

int main ()
{
  std::string str;
  std::string base="The quick brown fox jumps over a lazy dog.";

  // used in the same order as described above:

  str.assign(base);
  std::cout << str << '\n';

  str.assign(base,10,9);
  std::cout << str << '\n';         // "brown fox"

  str.assign("pangrams are cool",7);
  std::cout << str << '\n';         // "pangram"

  str.assign("c-string");
  std::cout << str << '\n';         // "c-string"

  str.assign(10,'*');
  std::cout << str << '\n';         // "**********"

  str.assign<int>(10,0x2D);
  std::cout << str << '\n';         // "----------"

  str.assign(base.begin()+16,base.end()-12);
  std::cout << str << '\n';         // "fox jumps over"

  return 0;
}

insert函数

在pos(或p)指示的字符之前的字符串中插入其他字符:

  1. string (1)

     string& insert (size_t pos, const string& str);
    
  2. substring (2)

     string& insert (size_t pos, const string& str, size_t subpos, size_t sublen);
    
  3. c-string (3)

     string& insert (size_t pos, const char* s);
    
  4. buffer (4)

     string& insert (size_t pos, const char* s, size_t n);
    
  5. fill (5)

     string& insert (size_t pos,   size_t n, char c);
     iterator insert (const_iterator p, size_t n, char c);
    
  6. single character (6)

     iterator insert (const_iterator p, char c);
    
  7. range (7)

     template <class InputIterator>
     iterator insert (iterator p, InputIterator first, InputIterator last);
    
  8. initializer list (8)

     string& insert (const_iterator p, initializer_list<char> il);
    

举例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>

int main ()
{
  std::string str="to be question";
  std::string str2="the ";
  std::string str3="or not to be";
  std::string::iterator it;

  // used in the same order as described above:
  str.insert(6,str2);                 // to be (the )question
  str.insert(6,str3,3,4);             // to be (not )the question
  str.insert(10,"that is cool",8);    // to be not (that is )the question
  str.insert(10,"to be ");            // to be not (to be )that is the question
  str.insert(15,1,':');               // to be not to be(:) that is the question
  it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
  str.insert (str.end(),3,'.');       // to be, not to be: that is the question(...)
  str.insert (it+2,str3.begin(),str3.begin()+3); // (or )

  std::cout << str << '\n';
  return 0;
}

erase函数

  1. sequence (1)

     string& erase (size_t pos = 0, size_t len = npos);
    
  2. character (2)

     iterator erase (const_iterator p);
    
  3. range (3)

     iterator erase (const_iterator first, const_iterator last);
    

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

int main ()
{
  std::string str ("This is an example sentence.");
  std::cout << str << '\n';
                                           // "This is an example sentence."
  str.erase (10,8);                        //            ^^^^^^^^
  std::cout << str << '\n';
                                           // "This is an sentence."
  str.erase (str.begin()+9);               //           ^
  std::cout << str << '\n';
                                           // "This is a sentence."
  str.erase (str.begin()+5, str.end()-9);  //       ^^^^^
  std::cout << str << '\n';
                                           // "This sentence."
  return 0;
}

replace函数

将以pos为开头,长度为len的子字符串替换为新内容.

  1. string (1)

     string& replace (size_t pos,        size_t len,        const string& str);
     string& replace (const_iterator i1, const_iterator i2, const string& str);
    
  2. substring (2)

     string& replace (size_t pos,        size_t len,        const string& str,
              size_t subpos, size_t sublen);
    
  3. 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);
    
  4. 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);
    
  5. 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);
    
  6. range (6)

     template <class InputIterator>
     	string& replace (const_iterator i1, const_iterator i2,
                InputIterator first, InputIterator last);
    
  7. initializer list (7)

     string& replace (const_iterator i1, const_iterator i2, initializer_list<char> il);
    

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <string>

int main ()
{
  std::string base="this is a test string.";
  std::string str2="n example";
  std::string str3="sample phrase";
  std::string str4="useful.";

  // replace signatures used in the same order as described above:

  // Using positions:                 0123456789*123456789*12345
  std::string str=base;           // "this is a test string."
  str.replace(9,5,str2);          // "this is an example string." (1)
  str.replace(19,6,str3,7,6);     // "this is an example phrase." (2)
  str.replace(8,10,"just a");     // "this is just a phrase."     (3)
  str.replace(8,6,"a shorty",7);  // "this is a short phrase."    (4)
  str.replace(22,1,3,'!');        // "this is a short phrase!!!"  (5)

  // Using iterators:                                               0123456789*123456789*
  str.replace(str.begin(),str.end()-3,str3);                    // "sample phrase!!!"      (1)
  str.replace(str.begin(),str.begin()+6,"replace");             // "replace phrase!!!"     (3)
  str.replace(str.begin()+8,str.begin()+14,"is coolness",7);    // "replace is cool!!!"    (4)
  str.replace(str.begin()+12,str.end()-4,4,'o');                // "replace is cooool!!!"  (5)
  str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());// "replace is useful."    (6)
  std::cout << str << '\n';
  return 0;
}

swap函数

void swap (string& str);

将该string与另一个string交换.

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>

main ()
{
  std::string buyer ("money");
  std::string seller ("goods");

  std::cout << "Before the swap, buyer has " << buyer;
  std::cout << " and seller has " << seller << '\n';

  seller.swap (buyer);

  std::cout << " After the swap, buyer has " << buyer;
  std::cout << " and seller has " << seller << '\n';

  return 0;
}

pop_back函数

删除字符串的最后一个字符,将其长度减少一个。

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <iostream>
#include <string>

int main ()
{
  std::string str ("hello world!");
  str.pop_back();
  std::cout << str << '\n';
  return 0;
}

字符串操作

c_str函数

const char* c_str() const noexcept;

返回一个指向数组的指针,该数组包含一个以空字符终止的字符序列(即C字符串),表示字符串对象的当前值。该数组包括组成字符串对象的值的相同序列,并在末尾加上另外的终止空字符(’\ 0’)。

举例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cstring>
#include <string>

int main ()
{
  std::string str ("Please split this sentence into tokens");

  char * cstr = new char [str.length()+1];
  std::strcpy (cstr, str.c_str());

  // cstr now contains a c-string copy of str

  char * p = std::strtok (cstr," ");
  while (p!=0)
  {
    std::cout << p << '\n';
    p = std::strtok(NULL," ");
  }

  delete[] cstr;
  return 0;
}

data函数

const char* data() const noexcept;

返回一个指向数组的指针,该数组包含一个以空字符终止的字符序列(即C字符串),表示字符串对象的当前值。

该数组包括组成字符串对象的值的相同序列,并在末尾加上另外的终止空字符(’\ 0’)。

返回的指针指向字符串对象当前使用的内部数组,以存储符合其值的字符。

string :: data和string :: c_str都是同义词,并返回相同的值。

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <cstring>

int main ()
{
  int length;

  std::string str = "Test string";
  char* cstr = "Test string";

  if ( str.length() == std::strlen(cstr) )
  {
    std::cout << "str and cstr have the same length.\n";

    if ( memcmp (cstr, str.data(), str.length() ) == 0 )
      std::cout << "str and cstr have the same content.\n";
  }
  return 0;
}

get_allocator函数

allocator_type get_allocator() const noexcept;

返回与该字符串关联的allocator对象的副本。 字符串使用默认 allocator类型,它没有状态(因此,返回的值与默认构造的分配器相同)。

copy函数

将字符串对象的当前值的子字符串复制到由s指向的数组中。此子字符串包含从位置pos开始的len字符。 该函数在复制的内容的末尾没有附加一个空字符。

复制到s指向的数组的字符数。这可能等于len或length()- pos(如果字符串值比pos + len短)。

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

s: 指向字符数组的指针。 数组应为复制的字符包含足够的存储空间。

len: 要复制的字符数(如果字符串较短,复制尽可能多的字符)。

pos: 要复制的第一个字符的位置。 如果这大于字符串长度,它将抛出out_of_range。 注意:字符串中的第一个字符由0(不是1)表示。

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <iostream>
#include <string>

int main ()
{
  char buffer[20];
  std::string str ("Test string...");
  std::size_t length = str.copy(buffer,6,5);
  buffer[length]='\0';
  std::cout << "buffer contains: " << buffer << '\n';
  return 0;
}

find函数

查找字符串中的内容

搜索由其参数指定的序列的第一次出现的字符串。

当指定pos时,搜索仅包含位置pos或之后的字符,忽略在pos之前包含字符的任何可能的事件。

请注意,与成员find_first_of不同,只要搜索多个字符,只有其中一个字符匹配是不够的,整个序列必须匹配。

返回第一场匹配的第一个字符的位置。 如果没有找到匹配,该函数返回string :: npos。

  1. string (1)

     size_t find (const string& str, size_t pos = 0) const noexcept;
    
  2. c-string (2)

     size_t find (const char* s, size_t pos = 0) const;
    
  3. buffer (3)

     size_t find (const char* s, size_t pos, size_type n) const;
    
  4. character (4)

     size_t find (char c, size_t pos = 0) const noexcept;
    

str:

搜索的字符串

pos:

搜索中要考虑的字符串中第一个字符的位置。 如果这大于字符串长度,该函数将永远不会找到匹配项。 注意:第一个字符由0(不是1)表示:值为0表示搜索整个字符串。

s:

指向字符数组的指针。 如果指定参数n,则要匹配的序列是数组s中的前n个字符。 否则要匹配的序列的长度由空字符的第一次出现确定。

n:

要匹配的字符序列长度

c:

要搜索的字符

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>       // std::cout
#include <string>         // std::string

int main ()
{
  std::string str ("There are two needles in this haystack with needles.");
  std::string str2 ("needle");

  // different member versions of find in the same order as above:
  std::size_t found = str.find(str2);
  if (found!=std::string::npos)
    std::cout << "first 'needle' found at: " << found << '\n';

  found=str.find("needles are small",found+1,6);
  if (found!=std::string::npos)
    std::cout << "second 'needle' found at: " << found << '\n';

  found=str.find("haystack");
  if (found!=std::string::npos)
    std::cout << "'haystack' also found at: " << found << '\n';

  found=str.find('.');
  if (found!=std::string::npos)
    std::cout << "Period found at: " << found << '\n';

  // let's replace the first needle:
  str.replace(str.find(str2),str2.length(),"preposition");
  std::cout << str << '\n';

  return 0;
}

rfind函数

查找字符串中的最后一个内容 搜索由其参数指定的序列的最后一次出现的字符串。

当指定pos时,搜索仅包括在位置pos之前或之后开始的字符序列,忽略在pos之后开始的任何可能的匹配。

返回最后一次匹配的第一个字符的位置。如果没有找到匹配,该函数返回string :: npos。

  1. string (1)

     size_t rfind (const string& str, size_t pos = npos) const noexcept;
    
  2. c-string (2)

     size_t rfind (const char* s, size_t pos = npos) const;
    
  3. buffer (3)

     size_t rfind (const char* s, size_t pos, size_t n) const;
    
  4. character (4)

     size_t rfind (char c, size_t pos = npos) const noexcept;
    

str:

搜索的字符串

pos:

字符串中最后一个字符的位置被视为匹配的开头。 任何大于或等于字符串长度的值(包括string :: npos)意味着搜索整个字符串。 注意:第一个字符由0(不是1)表示。

s:

指向字符数组的指针。 如果指定参数n,则要匹配的序列是数组中的前n个字符。 否则匹配的序列的长度由空字符的第一次出现确定。

n:

要匹配的字符序列长度

c:

要搜索的字符

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <cstddef>

int main ()
{
  std::string str ("The sixth sick sheik's sixth sheep's sick.");
  std::string key ("sixth");

  std::size_t found = str.rfind(key);
  if (found!=std::string::npos)
    str.replace (found,key.length(),"seventh");

  std::cout << str << '\n';

  return 0;
}

find_first_of函数

查找字符串中的字符

搜索与其参数中指定的任何字符匹配的第一个字符的字符串。 当指定pos时,搜索仅包含位置pos或之后的字符,忽略pos之前的任何可能的事件。

请注意,序列的一个字符匹配(不是全部)都足够了。请参阅string :: find查找与整个序列匹配的函数。

返回匹配的第一个字符的位置。如果没有找到匹配项,该函数返回string :: npos。

  1. string (1)

     size_t find_first_of (const string& str, size_t pos = 0) const noexcept;
    
  2. c-string (2)

     size_t find_first_of (const char* s, size_t pos = 0) const;
    
  3. buffer (3)

     size_t find_first_of (const char* s, size_t pos, size_t n) const;
    
  4. character (4)

     size_t find_first_of (char c, size_t pos = 0) const noexcept;
    

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

int main ()
{
  std::string str ("Please, replace the vowels in this sentence by asterisks.");
  std::size_t found = str.find_first_of("aeiou");
  while (found!=std::string::npos)
  {
    str[found]='*';
    found=str.find_first_of("aeiou",found+1);
  }

  std::cout << str << '\n';

  return 0;
}

find_last_of函数

从字符串中查找字符串 搜索与其参数中指定的任何字符匹配的最后一个字符的字符串。 当POS指定,搜索仅包括在字符或位置之前POS,忽略后的任何可能发生的POS。

返回匹配的最后一个字符的位置。如果没有找到匹配项,该函数返回string :: npos。

  1. string (1)

     size_t find_last_of (const string& str, size_t pos = npos) const noexcept;
    
  2. c-string (2)

     size_t find_last_of (const char* s, size_t pos = npos) const;
    
  3. buffer (3)

     size_t find_last_of (const char* s, size_t pos, size_t n) const;
    
  4. character (4)

     size_t find_last_of (char c, size_t pos = npos) const noexcept;
    

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>         // std::size_t

void SplitFilename (const std::string& str)
{
  std::cout << "Splitting: " << str << '\n';
  std::size_t found = str.find_last_of("/\\");
  std::cout << " path: " << str.substr(0,found) << '\n';
  std::cout << " file: " << str.substr(found+1) << '\n';
}

int main ()
{
  std::string str1 ("/usr/bin/man");
  std::string str2 ("c:\\windows\\winhelp.exe");

  SplitFilename (str1);
  SplitFilename (str2);

  return 0;
}

find_first_not_of函数

查找字符串中没有字符

搜索与其参数中指定的任何字符不匹配的第一个字符的字符串。

当指定pos时,搜索仅包含位置pos或之后的字符,忽略该字符之前的任何可能的事件。

  1. string (1)

     size_t find_first_not_of (const string& str, size_t pos = 0) const noexcept;
    
  2. c-string (2)

     size_t find_first_not_of (const char* s, size_t pos = 0) const;
    
  3. buffer (3)

     size_t find_first_not_of (const char* s, size_t pos, size_t n) const;
    
  4. character (4)

     size_t find_first_not_of (char c, size_t pos = 0) const noexcept;
    

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// string::find_first_not_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

int main ()
{
  std::string str ("look for non-alphabetic characters...");

  std::size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");

  if (found!=std::string::npos)
  {
    std::cout << "The first non-alphabetic character is " << str[found];
    std::cout << " at position " << found << '\n';
  }

  return 0;
}

find_last_not_of函数

从最后找到字符串中不匹配的字符

搜索与其参数中指定的任何字符不匹配的最后一个字符的字符串。

当POS指定,搜索仅包括在字符或位置之前POS,忽略后的任何可能发生的POS。

  1. string (1)

     size_t find_last_not_of (const string& str, size_t pos = npos) const noexcept;
    
  2. c-string (2)

     size_t find_last_not_of (const char* s, size_t pos = npos) const;
    
  3. buffer (3)

     size_t find_last_not_of (const char* s, size_t pos, size_t n) const;
    
  4. character (4)

     size_t find_last_not_of (char c, size_t pos = npos) const noexcept;
    

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>        // std::size_t

int main ()
{
  std::string str ("Please, erase trailing white-spaces   \n");
  std::string whitespaces (" \t\f\v\n\r");

  std::size_t found = str.find_last_not_of(whitespaces);
  if (found!=std::string::npos)
    str.erase(found+1);
  else
    str.clear();            // str is all whitespace

  std::cout << '[' << str << "]\n";

  return 0;
}

substr函数

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

生成子串

返回一个新建的 串对象的值初始化为该对象的子字符串的副本。

子字符串是从字符位置pos开始并跨越len个字符(或直到字符串的末尾,以先到者为准)的部分。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>

int main ()
{
  std::string str="We think in generalities, but we live in details.";
                                           // (quoting Alfred N. Whitehead)

  std::string str2 = str.substr (3,5);     // "think"

  std::size_t pos = str.find("live");      // position of "live" in str

  std::string str3 = str.substr (pos);     // get from "live" to the end

  std::cout << str2 << ' ' << str3 << '\n';

  return 0;
}

compare函数

比较字符串

将字符串对象(或子字符串)的值与其参数指定的字符序列进行比较。

返回一个整型值,表示字符串之间的关系.

  1. string (1)

     int compare (const string& str) const noexcept;
    
  2. 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) const;
    
  3. c-string (3)

     int compare (const char* s) const;
    
     int compare (size_t pos, size_t len, const char* s) const;
    
  4. buffer (4)

     int compare (size_t pos, size_t len, const char* s, size_t n) const;
    

示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>

int main ()
{
  std::string str1 ("green apple");
  std::string str2 ("red apple");

  if (str1.compare(str2) != 0)
    std::cout << str1 << " is not " << str2 << '\n';

  if (str1.compare(6,5,"apple") == 0)
    std::cout << "still, " << str1 << " is an apple\n";

  if (str2.compare(str2.size()-5,5,"apple") == 0)
    std::cout << "and " << str2 << " is also an apple\n";

  if (str1.compare(6,5,str2,4,5) == 0)
    std::cout << "therefore, both are apples\n";

  return 0;
}

重载

operator+

  1. string (1)

     string operator+ (const string& lhs, const string& rhs);
     string operator+ (string&&      lhs, string&&      rhs);
     string operator+ (string&&      lhs, const string& rhs);
     string operator+ (const string& lhs, string&&      rhs);
    
  2. c-string (2)

     string operator+ (const string& lhs, const char*   rhs);
     string operator+ (string&&      lhs, const char*   rhs);
     string operator+ (const char*   lhs, const string& rhs);
     string operator+ (const char*   lhs, string&&      rhs);
    
  3. character (3)

     string operator+ (const string& lhs, char          rhs);
     string operator+ (string&&      lhs, char          rhs);
     string operator+ (char          lhs, const string& rhs);
     string operator+ (char          lhs, string&&      rhs);
    

relational operators

(1)

bool operator== (const string& lhs, const string& rhs);
bool operator== (const char*   lhs, const string& rhs);
bool operator== (const string& lhs, const char*   rhs);

(2)

bool operator!= (const string& lhs, const string& rhs);
bool operator!= (const char*   lhs, const string& rhs);
bool operator!= (const string& lhs, const char*   rhs);

(3)

bool operator<  (const string& lhs, const string& rhs);
bool operator<  (const char*   lhs, const string& rhs);
bool operator<  (const string& lhs, const char*   rhs);

(4)

bool operator<= (const string& lhs, const string& rhs);
bool operator<= (const char*   lhs, const string& rhs);
bool operator<= (const string& lhs, const char*   rhs);

(5)

bool operator>  (const string& lhs, const string& rhs);
bool operator>  (const char*   lhs, const string& rhs);
bool operator>  (const string& lhs, const char*   rhs);

(6)

bool operator>= (const string& lhs, const string& rhs);
bool operator>= (const char*   lhs, const string& rhs);
bool operator>= (const string& lhs, const char*   rhs);