STL-string-2

这篇具有很好参考价值的文章主要介绍了STL-string-2。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Iterators

STL-string-2

 Capacity

STL-string-2

resize

void resize (size_t n);void resize (size_t n, char c);

Resize string

将字符串的大小调整为n个字符的长度。 如果n小于当前字符串长度,则当前值将缩短为其第一个n字符,删除第n个字符之后的字符。 如果n大于当前字符串长度,则通过在末尾插入所需数量的字符以达到n的大小来扩展当前内容。如果指定了c,则将新元素初始化为c的副本,否则,它们是值初始化字符(null字符)。

reserve

void reserve (size_t n = 0);

Request a change in capacity

请求字符串容量适应计划中的大小更改,最大长度为n个字符。 如果n大于当前字符串容量,则函数会使容器的容量增加到n个字符(或更多)。 在所有其他情况下,它被视为收缩字符串容量的非绑定请求:容器实现可以自由地进行其他优化,并使字符串的容量大于n。 此函数对字符串长度没有影响,也不能更改其内容。

shrink_to_fit

void shrink_to_fit();

Shrink to fit

请求字符串减小其容量以适应其大小。 该请求是非绑定的,容器实现可以自由地进行其他优化,并使字符串的容量大于其大小。 此函数对字符串长度没有影响,也不能更改其内容。

Element access

STL-string-2

 Modifiers

STL-string-2

 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);

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

// string::operator+=
#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;
}Output:
John K. Smith

append

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);

附加到字符串

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

(1) string

附加str的副本。

(2)  substring

附加str的子字符串的副本。子字符串是str的一部分,从字符位置subbase开始,跨越子字符串(或者直到str的末尾,如果str太短或子字符串为string::npos)。

(3)  c-string

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

(4) buffer

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

(5) fill

追加字符c的n个连续副本。

(6) range

以相同的顺序追加范围[第一个,最后一个)中的字符序列的副本。

(7)  initializer list

以相同的顺序追加il中每个字符的副本。

// appending to string
#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;
}Output:
Writing 10 dots here: .......... and then 5 more.....

push_back

void push_back (char c);

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

// 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;
}This example reads an entire file character by character, appending each character to a string object using push_back.

assign

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;

将内容分配给字符串

为字符串指定一个新值,替换其当前内容。

(1) string

复制str。

(2)  substring

复制str中从字符位置子组开始并跨越子组字符的部分(如果str太短或子组为string::npos,则复制到str的末尾)。

(3) c-string

复制s指向的以null结尾的字符序列(C字符串)。

(4) buffer

从s指向的字符数组中复制前n个字符。

(5) fill

用字符c的n个连续副本替换当前值。

(6) range

按相同顺序复制范围[第一个,最后一个)中的字符序列。

(7) initializer list

按照相同的顺序复制il中的每个字符。

(8)  move

获取str的内容。 str处于未指定但有效的状态。

// string::assign
#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;
}Output:
The quick brown fox jumps over a lazy dog.
brown fox
pangram
c-string
**********
----------
fox jumps over

insert

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);

插入字符串

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

(1)string

插入str的副本。

(2)substring

插入str的子字符串的副本。该子字符串是str的一部分,该部分从字符位置subbase开始,跨越子字符串字符(或者直到str的末尾,如果str太短或子字符串为npos)。

(3)c-string

插入由s指向的以null结尾的字符序列(C字符串)形成的字符串的副本。

(4)buffer

在由s指向的字符数组中插入前n个字符的副本。

(5)fill

插入字符c的n个连续副本。

(6)single character

插入字符c。

(7)range

以相同的顺序插入范围[第一个,最后一个)中的字符序列的副本。

(8)initializer list

按照相同的顺序插入il中每个字符的副本。 size_t是一个无符号整数类型(与成员类型string::size_type相同)。

// inserting into a string
#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;
}Output:
to be, or not to be: that is the question...

erase

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);

删除字符串中的字符

擦除字符串的一部分,缩短其长度:

(1)sequence

删除字符串值中从字符位置pos开始并跨越len个字符的部分(或者,如果内容太短或len为string::npos,则直到字符串结束)。 请注意,默认参数会擦除字符串中的所有字符(类似于成员函数clear)。

(2)character

删除p所指的字符。

(3)range

删除范围[第一个,最后一个]中的字符序列。

// string::erase
#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;
}Output:
This is an example sentence.
This is an sentence.
This is a sentence.
This sentence.

replace

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 = npos);
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);

替换字符串的一部分

将字符串中从字符pos开始并跨越len个字符的部分(或[i1,i2)之间范围内的部分)替换为新内容:

(1)string

复制str。

(2)substring

复制str中从字符位置子组开始并跨越子组字符的部分(如果str太短或子组为string::npos,则复制到str的末尾)。

(3)c-string

复制s指向的以null结尾的字符序列(C字符串)。

(4)buffer

从s指向的字符数组中复制前n个字符。

(5)fill

用字符c的n个连续副本替换字符串的部分。

(6)range

按相同顺序复制范围[第一个,最后一个)中的字符序列。

(7)initializer list

按照相同的顺序复制il中的每个字符。

// replacing in a string
#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;
}Output:
replace is useful.

swap

void swap (string& str);

交换字符串值

通过str的内容交换容器的内容,str是另一个字符串对象。长度可能不同。 在调用该成员函数之后,该对象的值是str在调用之前的值,str的值是该对象在调用之前具有的值。 请注意,存在一个具有相同名称的非成员函数,即swap,用类似于该成员函数的优化重载该算法。

// swap strings
#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;
}
Output:
Before the swap, buyer has money and seller has goods
 After the swap, buyer has goods and seller has money

pop_back

void pop_back();

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

// string::pop_back
#include <iostream>
#include <string>

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

String operations

STL-string-2

c_str

const char* c_str() const noexcept;

 获取等效的C字符串

返回一个指向数组的指针,该数组包含一个以null结尾的字符序列(即C字符串),表示字符串对象的当前值。 此数组包含组成字符串对象值的相同字符序列,加上末尾的附加终止null字符(“\0”)。

// strings and c-strings
#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;
}Output:
Please
split
this
sentence
into
tokens

data

const char* data() const noexcept;

Get string data

返回一个指向数组的指针,该数组包含一个以null结尾的字符序列(即C字符串),表示字符串对象的当前值。 此数组包含组成字符串对象值的相同字符序列,加上末尾的附加终止null字符(“\0”)。 指针返回指向字符串对象当前用于存储符合其值的字符的内部数组。 字符串::data和字符串::c_str都是同义词,返回相同的值。

// string::data
#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;
}Output:
str and cstr have the same length.
str and cstr have the same content.

get_allocator

allocator_type get_allocator() const noexcept;

获取分配器

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

copy

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

从字符串中复制字符序列

将字符串对象的当前值的子字符串复制到s指向的数组中。该子字符串包含从位置pos开始的len字符。 函数不会在复制内容的末尾附加null字符。

// string::copy
#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;
}Output:
buffer contains: string

find

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;

在字符串中查找内容

在字符串中搜索由其参数指定的序列的第一个匹配项。 指定pos时,搜索仅包括位置pos处或之后的字符,忽略任何可能出现的位置pos之前的字符。 请注意,与成员find_first_of不同,无论何时搜索多个字符,仅匹配其中一个字符是不够的,但必须匹配整个序列。

// string::find
#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;
}Notice how parameter pos is used to search for a second instance of the same search string. Output:
first 'needle' found at: 14
second 'needle' found at: 44
'haystack' also found at: 30
Period found at: 51
There are two prepositions in this haystack with needles.

rfind

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

查找字符串中最后一次出现的内容

在字符串中搜索由其参数指定的序列的最后一次出现。 指定pos时,搜索仅包括从位置pos开始或在位置pos之前的字符序列,忽略从pos之后开始的任何可能的匹配。

// string::rfind
#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;
}The sixth sick sheik's seventh sheep's sick. 

find_first_of

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;

查找字符串中的字符

在字符串中搜索与其参数中指定的任何字符匹配的第一个字符。 指定位置时,搜索仅包括位置位置处或位置之后的字符,忽略位置之前可能出现的任何字符。 请注意,序列中的一个字符(不是所有字符)匹配就足够了。请参阅string::find以获取与整个序列匹配的函数。

// string::find_first_of
#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;
}Pl**s*, r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks. 

find_last_of

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

从字符串末尾查找字符

在字符串中搜索与其参数中指定的任何字符匹配的最后一个字符。 指定位置时,搜索仅包括位置位置处或位置之前的字符,忽略位置之后可能出现的任何字符。

// string::find_last_of
#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;
}
Splitting: /usr/bin/man
 path: /usr/bin
 file: man
Splitting: c:\windows\winhelp.exe
 path: c:\windows
 file: winhelp.exe

find_first_not_of

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

查找字符串中缺少字符

在字符串中搜索与参数中指定的任何字符都不匹配的第一个字符。 当指定了pos时,搜索只包括位置pos处或之后的字符,忽略该字符之前可能出现的任何字符。

// 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;
}The first non-alphabetic character is - at position 12 

find_last_not_of

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

从末尾开始查找字符串中不匹配的字符

在字符串中搜索与参数中指定的任何字符都不匹配的最后一个字符。 指定位置时,搜索仅包括位置位置处或位置之前的字符,忽略位置之后可能出现的任何字符。

// string::find_last_not_of
#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;
}[Please, erase trailing white-spaces] 

substr

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

生成子字符串

返回一个新构造的字符串对象,该对象的值初始化为此对象的子字符串的副本。 子字符串是对象中从字符位置pos开始并跨越len个字符(或直到字符串结束,以先到者为准)的部分。

// string::substr
#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;
}
Output:
think live in details.

compare

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;

比较字符串

将字符串对象(或子字符串)的值与其参数指定的字符序列进行比较。 比较的字符串是字符串对象的值,或者如果使用的签名有pos和len参数,则是从位置pos的字符开始并跨越len个字符的子字符串。 将此字符串与比较字符串进行比较,比较字符串由传递给函数的其他参数决定。

// comparing apples with apples
#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;
}Output:
green apple is not red apple
still, green apple is an apple
and red apple is also an apple
therefore, both are apples

Non-member function overloads

STL-string-2

operator+ (string)

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);
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);
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);
// concatenating strings
#include <iostream>
#include <string>

main ()
{
  std::string firstlevel ("com");
  std::string secondlevel ("cplusplus");
  std::string scheme ("http://");
  std::string hostname;
  std::string url;

  hostname = "www." + secondlevel + '.' + firstlevel;
  url = scheme + hostname;

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

  return 0;
}Output:
http://www.cplusplus.com

relational operators (string)

(1)
bool operator== (const string& lhs, const string& rhs) noexcept;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) noexcept;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) noexcept;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) noexcept;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) noexcept;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) noexcept;bool operator>= (const char*   lhs, const string& rhs);bool operator>= (const string& lhs, const char*   rhs);

字符串的关系运算符

在字符串对象lhs和rhs之间执行适当的比较操作。 函数使用字符串::compare进行比较。 这些运算符在标头<string>中重载。

// string comparisons
#include <iostream>
#include <vector>

int main ()
{
  std::string foo = "alpha";
  std::string bar = "beta";

  if (foo==bar) std::cout << "foo and bar are equal\n";
  if (foo!=bar) std::cout << "foo and bar are not equal\n";
  if (foo< bar) std::cout << "foo is less than bar\n";
  if (foo> bar) std::cout << "foo is greater than bar\n";
  if (foo<=bar) std::cout << "foo is less than or equal to bar\n";
  if (foo>=bar) std::cout << "foo is greater than or equal to bar\n";

  return 0;
}Output:
foo and bar are not equal
foo is less than bar
foo is less than or equal to bar

swap (string)

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

交换两个字符串的值

交换字符串对象x和y的值,这样在调用该函数后,x的值就是调用前y上的值,y的值就是x的值。 这是通用算法交换的过载,通过将其内部数据的所有权相互转移到另一个对象来提高其性能(即,字符串交换对其数据的引用,而不实际复制字符):它的行为就像调用了x.swap(y)。

// swap strings
#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';

  swap (buyer,seller);

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

  return 0;
}Output:
Before the swap, buyer has money and seller has goods
 After the swap, buyer has goods and seller has money

operator>> (string)

istream& operator>> (istream& is, string& str);

从流中提取字符串

从输入流is中提取一个字符串,将序列存储在str中,该字符串将被覆盖(str的前一个值将被替换)。 此函数重载运算符>>,使其行为如istream::operator>>中对c字符串所述,但应用于字符串对象。 每个提取的字符都被附加到字符串中,就好像调用了其成员push_back一样。 请注意,istream提取操作使用空格作为分隔符;因此,此操作将仅从流中提取可以被视为单词的内容。要提取整行文本,请参阅全局函数getline的字符串重载。

// extract to string
#include <iostream>
#include <string>

main ()
{
  std::string name;

  std::cout << "Please, enter your name: ";
  std::cin >> name;
  std::cout << "Hello, " << name << "!\n";

  return 0;
}

operator<< (string)

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

将字符串插入流

将符合str值的字符序列插入os。 对于c字符串,此函数重载运算符<<,使其行为如ostream::运算符<<中所述,但应用于字符串对象。

// inserting strings into output streams
#include <iostream>
#include <string>

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

getline (string)

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

将行从流转换为字符串

从is中提取字符并将其存储到str中,直到找到定界字符delim(或换行符'\n',表示(2))。 如果在is中到达文件末尾,或者在输入操作过程中发生其他错误,提取也会停止。 如果找到了分隔符,则提取并丢弃它(即不存储它,并在它之后开始下一个输入操作)。 请注意,调用之前str中的任何内容都会被新提取的序列所取代。 每个提取的字符都被附加到字符串中,就好像调用了其成员push_back一样。文章来源地址https://www.toymoban.com/news/detail-487476.html

// extract to string
#include <iostream>
#include <string>

int main ()
{
  std::string name;

  std::cout << "Please, enter your full name: ";
  std::getline (std::cin,name);
  std::cout << "Hello, " << name << "!\n";

  return 0;
}

到了这里,关于STL-string-2的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【STL】string类 (下)

    目录 1,insert 2,erase 3,find 4,replace 5,rfind 6,substr 7,find_first_of 8,find_first_not_of 9,find_last_of 10,operator+ 11,getline 在 pos 位置之前插入字符串 擦除范围字符串 从 pos 位置开始,用 n 个字符替换; 上述可以看到,第一个替换从下标 0 开始用两个字符也就是 ” he “ 替换 “

    2024年02月05日
    浏览(57)
  • 【STL】string的使用

    放在专栏【 C++知识总结 】,会持续更新,期待支持 🌹 STL为英文Standard Template Library的缩写,译为 标准模板库 。 是C++标准库的重要组成部分 。 长久以来,软件届一直希望建立一种可重复运用的东西。所谓的泛型思想以及面向对象最主要的目的就是为了复用性的提升 复用性

    2024年02月05日
    浏览(50)
  • 【c++】STL--string

            最开始我们学习c语言的时候,我们发现刷题或者写代码都是比较麻烦的,如果说用c语言造一辆车,那么我需要用c语言先把轮子造好--各个零件,当我们造好之后再组装。那么c++则是造好了轮子,只需要我们组装就好了。这里的的STL里有各个组件,我只要熟悉的掌握

    2024年02月03日
    浏览(39)
  • 【STL】手撕 string类

    目录 1,string类框架 2,string(构造) 3,~string(析构) 4,swap(交换) 5,string(拷贝构造) 1,常规法 2,简便法 6,size (字符长度) 7,c_str(返回字符形式的指针) 8,iterator(迭代器) 9,operator=(赋值) 1,常规写法 2,简便法 10,operator[](取值) 11,reserve(空间容量

    2024年02月04日
    浏览(32)
  • STL string

    计算机中只能存储二进制,不能存储现实生活中的文字,于是需要对文字进行编码 输入文字时,计算机根据编码表,将文字转换为对应的二进制,输出文字时,计算机根据编码表,将二进制转换为对应的文字 ASCII 码就是为了可以在计算机中存储和显示英文信息 由于计算机的

    2024年02月12日
    浏览(30)
  • C++ STL string类

    目录 一.为什么学习string类 (1) C语言中的字符串 (2)标准库里面的string类 二. string类的常用接口说明 (1)string类对象的常见构造 (2)string类对象的容量操作 1.size(),length(). 2. capacity() 3.empty()  4.clear()  5.reserve()  6.resize() (3)string类对象的访问及遍历操作  1.operator[ pos

    2024年02月13日
    浏览(26)
  • STL常用容器—string容器

    本质: string是C++风格的字符串,而string本质上是一个类 string和char * 区别: char * 是一个指针 string是一个类,类内部封装了char *,管理这个字符串,是一个char *型的容器。 特点: string 类内部封装了很多成员属性和方法 string管理char*所分配的内存,不用担心复制越界和取值越

    2024年01月16日
    浏览(31)
  • <C++_STL> string

    C语言中, 字符串 是以 \\\'\\0\\\' 结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数, 但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会 越界访问 。 1.string类是表示字符序列的类 2.标准的st

    2024年02月03日
    浏览(26)
  • 【C++】STL——string类详解

    🚀 作者简介:一名在后端领域学习,并渴望能够学有所成的追梦人。 🚁 个人主页:不 良 🔥 系列专栏:🛸C++  🛹Linux 📕 学习格言:博观而约取,厚积而薄发 🌹 欢迎进来的小伙伴,如果小伙伴们在学习的过程中,发现有需要纠正的地方,烦请指正,希望能够与诸君一同

    2024年02月11日
    浏览(31)
  • 【C++】STL——string(两万字详解)

    🎇C++学习历程:STL——string学习 博客主页: 一起去看日落吗 持续分享博主的C++学习历程 博主的能力有限,出现错误希望大家不吝赐教 分享给大家一句我很喜欢的话: 也许你现在做的事情,暂时看不到成果,但不要忘记,树🌿成长之前也要扎根,也要在漫长的时光🌞中沉

    2024年01月25日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包