1. 程式人生 > >C++ string 常見函式一覽

C++ string 常見函式一覽

1 std::string::back & front

      char& back();

const char& back() const;

Access last character

Returns a reference to the last character of the string.

This function shall not be called on empty strings.

     char& front();

const char& front() const;

Access first character

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.

Example

// string::back

#include <iostream>

#include <string>

int main ()

{

  std::string str ("hello world."

);

str.front() = 'H';

  str.back() = '!';

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

  return 0;

}

Output:

Hello world!

2std::string::push_back & pop_back

void push_back (char c);

Append character to string

Appends character c to the end of the string, increasing its length by one.

void pop_back();

Delete last character

Erases the last character of the string, effectively reducing its length by one.

Example

// string::pop_back

#include <iostream>

#include <string>

int main ()

{

  std::string str ("hello world!");

  str.pop_back();

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

  str.push_back(‘!’);

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

  return 0;

}

Output:

hello world

hello world!

3 std::string::append

string (1)

string& append (const string& str);

substring (2)

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

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

Append to string

Extends the string by appending additional characters at the end of its current value:

(1) string

Appends a copy of str.

(2) substring

Appends a copy of a substring of str. The substring is the portion of str that begins at the character position subposand spans sublen characters (or until the end of str, if either str is too short or if sublen is string::npos).

(3) c-string

Appends a copy of the string formed by the null-terminated character sequence (C-string) pointed by s.

(4) buffer

Appends a copy of the first n characters in the array of characters pointed by s.

(5) fill

Appends n consecutive copies of character c.

(6) range

Appends a copy of the sequence of characters in the range [first,last), in the same order.

(7) initializer list

Appends a copy of each of the characters in il, in the same order.

Example

// 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.....

4 std::string::assign

string (1)

string& assign (const string& str);

substring (2)

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

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;

Assign content to string

Assigns a new value to the string, replacing its current contents.

(1) string

Copies str.

(2) substring

Copies the portion of str that begins at the character position subpos and spans sublen characters (or until the end of str, if either str is too short or if sublen is string::npos).

(3) c-string

Copies the null-terminated character sequence (C-string) pointed by s.

(4) buffer

Copies the first n characters from the array of characters pointed by s.

(5) fill

Replaces the current value by n consecutive copies of character c.

(6) range

Copies the sequence of characters in the range [first,last), in the same order.

(7) initializer list

Copies each of the characters in il, in the same order.

(8) move

Acquires the contents of str.
str is left in an unspecified but valid state.

Example

// 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

5 std::string::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);

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

Insert into string

Inserts additional characters into the string right before the character indicated by pos (or p):

(1) string

Inserts a copy of str.

(2) substring

Inserts a copy of a substring of str. The substring is the portion of str that begins at the character position subposand spans sublen characters (or until the end of str, if either str is too short or if sublen is npos).

(3) c-string

Inserts a copy of the string formed by the null-terminated character sequence (C-string) pointed by s.

(4) buffer

Inserts a copy of the first n characters in the array of characters pointed by s.

(5) fill

Inserts n consecutive copies of character c.

(6) single character

Inserts character c.

(7) range

Inserts a copy of the sequence of characters in the range [first,last), in the same order.

(8) initializer list

Inserts a copy of each of the characters in il, in the same order.


size_t is an unsigned integral type (the same as member type string::size_type).

Return value

The signatures returning a reference to string, return *this.
Those returning an iterator, return an iterator pointing to the first character inserted.

Example

// 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...

6 std::string::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);

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

Replace portion of string

Replaces the portion of the string that begins at character pos and spans len characters (or the part of the string in the range between [i1,i2)) by new contents:

(1) string

Copies str.

(2) substring

Copies the portion of str that begins at the character position subpos and spans sublen characters (or until the end of str, if either str is too short or if sublen is string::npos).

(3) c-string

Copies the null-terminated character sequence (C-string) pointed by s.

(4) buffer

Copies the first n characters from the array of characters pointed by s.

(5) fill

Replaces the portion of the string by n consecutive copies of character c.

(6) range

Copies the sequence of characters in the range [first,last), in the same order.

(7) initializer list

Copies each of the characters in il, in the same order.

Example

// 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.

7 std::string::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);

Erase characters from string

Erases part of the string, reducing its length:

(1) sequence

Erases the portion of the string value that begins at the character position pos and spans len characters (or until the end of the string, if either the content is too short or if len is string::npos.
Notice that the default argument erases all characters in the string (like member function clear).

(2) character

Erases the character pointed by p.

(3) range

Erases the sequence of characters in the range [first,last).

Example

// string::erase

#include <iostream>

#include <string>

int main ()

{

  std::string str ("This is an example sentence.");

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

                                           // "This is anexamplesentence."

  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.

8 std::string::empty

bool empty() const noexcept;

Test if string is empty

Returns whether the string is empty (i.e. whether its length is 0).

This function does not modify the value of the string in any way. To clear the content of a string, see string::clear.

Example

// string::empty

#include <iostream>

#include <string>

int main ()

{

  std::string content;

  std::string line;

  std::cout << "Please introduce a text. Enter an empty line to finish:\n";

  do {

    getline(std::cin,line);

    content += line + '\n';

  } while (!line.empty());

  std::cout << "The text you introduced was:\n" << content;

  return 0;

}

9 std::string::copy

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

Copy sequence of characters from string

Copies a substring of the current value of the string object into the array pointed by s. This substring contains the lencharacters that start at position pos.

The function does not append a null character at the end of the copied content.

Return value

The number of characters copied to the array pointed by s. This may be equal to len or to length()-pos (if the string value is shorter than pos+len).

size_t is an unsigned integral type (the same as member type string::size_type).

Example

// 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

10 std::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;

Find content in string

Searches the string for the first occurrence of the sequence specified by its arguments.

When pos is specified, the search only includes characters at or after position pos, ignoring any possible occurrences that include characters before pos.

Notice that unlike member find_first_of, whenever more than one character is being searched for, it is not enough that just one of these characters match, but the entire sequence must match.

Return Value

The position of the first character of the first match.
If no matches were found, the function returns string::npos.

size_t is an unsigned integral type (the same as member type string::size_type).

Example

// 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.

11 std::string::substr

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

Generate substring

Returns a newly constructed string object with its value initialized to a copy of a substring of this object.

The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first).

Return Value

string object with a substring of this object.

Example

// 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.

12 std::string::c_str & data

const char* c_str() const noexcept;

Get C string equivalent

Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.

This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character ('\0') at the end.

const char* data() const noexcept;

Return Value

A pointer to the c-string representation of the string object's value.

Example

123456789101112131415161718192021222324

// 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

Example

123456789101112131415161718192021

// 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.

13 std::string::swap

void swap (string& str);

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.

Notice that a non-member function exists with the same name, swap, overloading that algorithm with an optimization that behaves like this member function.

Example

12345678910111213141516171819

// 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