C++:std::string 的使用

目录

std::string

string概述

成员类型

成员函数

(constructor) 构造函数

(destructor) 析构函数

operator= 赋值

迭代器相关

容器大小或容量相关

成员访问相关

*添加、删除等修改相关操作*

字符串操作

成员常量

*重载的非成员函数*


std::string

namespace std{
    class string
    {
       public:
            string(const char*a){}
        
       private:
           char *str;
    }
}

string概述

typedef basic_string string;

  字符串是表示字符序列的对象。   

        标准string类使用类似于字节标准容器的接口提供对此类对象的支持,但是添加了专门用于操作单字节字符(single-byte characters)的字符串的特性。   

        string类是basic_string类模板的实例化,该模板使用char作为其字符类型,并具有默认的char_traits和allocator类型。   

        需要注意的是,这个类独立于所使用的编码来处理字节(即与编码无关):如果用于处理多字节或可变长度字符(如UTF-8)的序列,那么这个类的所有成员(如长度或大小)及其迭代器仍将以字节(而不是实际编码的字符)进行操作。

成员类型

member type definition
value_type char
traits_type char_traits
allocator_type allocator
reference char&
const_reference const char&
pointer char*
const_pointer const char*
iterator a random access iterator to char (convertible to const_iterator)
const_iterator a random access iterator to const char
reverse_iterator reverse_iterator
const_reverse_iterator reverse_iterator
difference_type ptrdiff_t
size_type size_t

成员函数

  • (constructor) 构造函数

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 string (InputIterator first, InputIterator last);
initializer list (8) string (initializer_list il);
move (9) string (string&& str) noexcept;
  • (destructor) 析构函数

    ~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 il);
move (5) string& operator= (string&& str) noexcept;
  • 迭代器相关

函数 函数原型 功能描述
begin iterator begin() noexcept; Return iterator to beginning
const_iterator begin() const noexcept;
end iterator end() noexcept; Return iterator to end
const_iterator end() const noexcept;
rbegin reverse_iterator rbegin() noexcept; Return reverse iterator to reverse beginning
const_reverse_iterator rbegin() const noexcept;
rend reverse_iterator rend() noexcept; Return reverse iterator to reverse end
const_reverse_iterator rend() const noexcept;
cbegin const_iterator cbegin() const noexcept; Return const_iterator to beginning
cend const_iterator cend() const noexcept; Return const_iterator to end
crbegin const_reverse_iterator crbegin() const noexcept; Return const_reverse_iterator to reverse beginning
crend const_reverse_iterator crend() const noexcept; Return const_reverse_iterator to reverse end

 迭代器示例:

// string::begin/end
#include 
#include 
​
int main ()
{
  std::string str ("Test string");
  for ( std::string::iterator it=str.begin(); it!=str.end(); ++it)
{
    std::cout << str;
  std::cout << '\n';
​}
  return 0;
}
​
Output:
Test string
  • 容器大小或容量相关

函数 函数原型 功能描述
size size_t size() const noexcept; Return length of string
length size_t length() const noexcept; Return length of string
max_size size_t max_size() const noexcept; Return maximum size of string
resize void resize (size_t n); Resize string
void resize (size_t n, const value_type& val);
capacity size_t capacity() const noexcept; Return size of allocated storage
reserve void reserve (size_t n = 0); Request a change in capacity
clear void clear() noexcept; Clear string
empty bool empty() const noexcept; Test if string is empty
shrink_to_fit void shrink_to_fit(); Shrink to fit

  示例:

// resizing string
#include 
#include 
​
int main ()
{
  std::string str ("I like to code in C");
  std::cout << str << '\n';
​
  unsigned sz = str.size();
​
  str.resize (sz+2,'+');
  std::cout << str << '\n';
​
  str.resize (14);
  std::cout << str << '\n';
  return 0;
}
​
Output:
I like to code in C
I like to code in C++
I like to code
----------------------------------------------------------
// comparing size, length, capacity and max_size
#include 
#include 
​
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;
}
​
A possible output for this program could be:
size: 11
length: 11
capacity: 15
max_size: 429496729
  • 成员访问相关

函数 函数原型 功能描述
operator[] char& operator[] (size_t pos); 获取字符串的字符
const char& operator[] (size_t pos) const;
at char& at (size_t pos); 获取字符串的字符
const char& at (size_t pos) const;
front reference front(); 访问最后一个字符
const_reference front() const;
back char& back(); 访问第一个字符
const char& back() const;

  成员访问示例:

// string::operator[]
#include 
#include 
​using namespace std;

int main ()
{
  std::string str ("Test string");
  for (int i=0; i
------------------------------------------------------

// string::at
#include 
#include 
​​using namespace std;
int main ()
{
  std::string str ("Test string");
  for (unsigned i=0; i
------------------------------------------------------

// string::front
#include 
#include 
​
int main ()
{
  std::string str ("test string");
  str.front() = 'T';
  std::cout << str << '\n';
  return 0;
}
​
Output:
Test string
------------------------------------------------------

// string::back
#include 
#include 
​
int main ()
{
  std::string str ("hello world.");
  str.back() = '!';
  std::cout << str << '\n';
  return 0;
}
​
Output:
hello world!
 
  
  • *添加、删除等修改相关操作*

函数 函数原型 功能描述
operator+= string& operator+= (const string& str); 附加到字符串
string& operator+= (const char* s);
string& operator+= (char c);
string& operator+= (initializer_list il);
append string& append (const string& str); 附加到字符串
string& append (const string& str, size_t subpos, size_t sublen);
string& append (const char* s);
string& append (const char* s, size_t n);
string& append (size_t n, char c);
template string& append (InputIterator first, InputIterator last);
string& append (initializer_list il);
push_back void push_back (char c); 将字符追加到字符串
assign string& assign (const string& str); 将内容赋值给字符串
string& assign (const string& str, size_t subpos, size_t sublen);
string& assign (const char* s);
string& assign (const char* s, size_t n);
string& assign (size_t n, char c);
template string& assign (InputIterator first, InputIterator last);
string& assign (initializer_list il);
string& assign (string&& str) noexcept;
insert string& insert (size_t pos, const string& str); 插入字符串
string& insert (size_t pos, const string& str, size_t subpos, size_t sublen);
string& insert (size_t pos, const char* s);
string& insert (size_t pos, const char* s, size_t n);
string& insert (size_t pos, size_t n, char c); iterator insert (const_iterator p, size_t n, char c);
iterator insert (const_iterator p, char c);
template iterator insert (iterator p, InputIterator first, InputIterator last);
string& insert (const_iterator p, initializer_list il);
erase string& erase (size_t pos = 0, size_t len = npos); 删除字符串中的字符
iterator erase (const_iterator p);
iterator erase (const_iterator first, const_iterator last);
replace string& replace (size_t pos, size_t len, const string& str); string& replace (const_iterator i1, const_iterator i2, const string& str); 替换字符串的一部分
string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);
string& replace (size_t pos, size_t len, const char* s); string& replace (const_iterator i1, const_iterator i2, const char* s);
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);
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);
template string& replace (const_iterator i1, const_iterator i2, InputIterator first, InputIterator last);
string& replace (const_iterator i1, const_iterator i2, initializer_list il);
swap void swap (string& str); 交换字符串值
pop_back void pop_back(); 删除最后一个字符

  示例:

// string::operator+=
#include 
#include 
​
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
------------------------------------------------------------

// appending to string
#include 
#include 
​
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(5,0x2E);                // "....."
​
  std::cout << str << '\n';
  return 0;
}
​
Output:
Writing 10 dots here: .......... and then 5 more.....
------------------------------------------------------------

// string::push_back
#include 
#include 
#include 
​
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;
}
------------------------------------------------------------

// string::assign
#include 
#include 
​
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(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
------------------------------------------------------------

// inserting into a string
#include 
#include 
​
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...
------------------------------------------------------------

// string::erase
#include 
#include 
​
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.
------------------------------------------------------------

// replacing in a string
#include 
#include 
​
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 strings
#include 
#include 
​
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
------------------------------------------------------------

// string::pop_back
#include 
#include 
​
int main ()
{
  std::string str ("hello world!");
  str.pop_back();
  std::cout << str << '\n';
  return 0;
}
​
Output:
hello world
 
  
  • 字符串操作

函数 函数原型 功能描述
c_str const char* c_str() const noexcept; Get C string equivalent
data const char* data() const noexcept; Get string data
get_allocator allocator_type get_allocator() const noexcept; Get allocator
copy size_t copy (char* s, size_t len, size_t pos = 0) const; Copy sequence of characters from string
find size_t find (const string& str, size_t pos = 0) const noexcept; Find content in string
size_t find (const char* s, size_t pos = 0) const;
size_t find (const char* s, size_t pos, size_type n) const;
size_t find (char c, size_t pos = 0) const noexcept;
rfind size_t rfind (const string& str, size_t pos = npos) const noexcept; Find last occurrence of content in string
size_t rfind (const char* s, size_t pos = npos) const;
size_t rfind (const char* s, size_t pos, size_t n) const;
size_t rfind (char c, size_t pos = npos) const noexcept;
find_first_of size_t find_first_of (const string& str, size_t pos = 0) const noexcept; Find character in string. Searches the string for the first character that matches any of the characters specified in its arguments.
size_t find_first_of (const char* s, size_t pos = 0) const;
size_t find_first_of (const char* s, size_t pos, size_t n) const;
size_t find_first_of (char c, size_t pos = 0) const noexcept;
find_last_of size_t find_last_of (const string& str, size_t pos = npos) const noexcept; Find character in string from the end. Searches the string for the last character that matches any of the characters specified in its arguments.
size_t find_last_of (const char* s, size_t pos = npos) const;
size_t find_last_of (const char* s, size_t pos, size_t n) const;
size_t find_last_of (char c, size_t pos = npos) const noexcept;
find_first_not_of size_t find_first_not_of (const string& str, size_t pos = 0) const noexcept; Find absence of character in string. Searches the string for the first character that does not match any of the characters specified in its arguments.
size_t find_first_not_of (const char* s, size_t pos = 0) const;
size_t find_first_not_of (const char* s, size_t pos, size_t n) const;
size_t find_first_not_of (char c, size_t pos = 0) const noexcept;
find_last_not_of size_t find_last_not_of (const string& str, size_t pos = npos) const noexcept; Find non-matching character in string from the end. Searches the string for the last character that does not match any of the characters specified in its arguments.
size_t find_last_not_of (const char* s, size_t pos = npos) const;
size_t find_last_not_of (const char* s, size_t pos, size_t n) const;
size_t find_last_not_of (char c, size_t pos = npos) const noexcept;
substr string substr (size_t pos = 0, size_t len = npos) const; Generate substring
compare int compare (const string& str) const noexcept; Compare strings
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;
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;
int compare (size_t pos, size_t len, const char* s, size_t n) const;

成员常量

npos static const size_t npos = -1; Maximum value for size_t

  当用作string成员函数中len(或sublen)参数的值时,其表示“直到字符串结束”。而作为返回值时,它通常用于表示不匹配。

*重载的非成员函数*

函数 函数原型 功能描述
operator+ string operator+ (const string& lhs, const string& rhs); Concatenate strings
string operator+ (string&& lhs, string&& rhs);
string operator+ (string&& lhs, const string& rhs);
string operator+ (const string& lhs, string&& rhs);
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);
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 bool operator== (const string& lhs, const string& rhs); Relational operators for string
bool operator== (const char* lhs, const string& rhs);
bool operator== (const string& lhs, const char* rhs);
bool operator!= (const string& lhs, const string& rhs);
bool operator!= (const char* lhs, const string& rhs);
bool operator!= (const string& lhs, const char* rhs);
bool operator< (const string& lhs, const string& rhs);
bool operator< (const char* lhs, const string& rhs);
bool operator< (const string& lhs, const char* rhs);
bool operator<= (const string& lhs, const string& rhs);
bool operator<= (const char* lhs, const string& rhs);
bool operator<= (const string& lhs, const char* rhs);
bool operator> (const string& lhs, const string& rhs);
bool operator> (const char* lhs, const string& rhs);
bool operator> (const string& lhs, const char* rhs);
bool operator>= (const string& lhs, const string& rhs);
bool operator>= (const char* lhs, const string& rhs);
bool operator>= (const string& lhs, const char* rhs);
swap void swap (string& x, string& y); Exchanges the values of two strings
operator>> istream& operator>> (istream& is, string& str); Extract string from stream
operator<< ostream& operator<< (ostream& os, const string& str); Insert string into stream
getline istream& getline (istream& is, string& str, char delim); Get line from stream into string
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream& is, string& str);
istream& getline (istream&& is, string& str);

注:std::string功能还不是很完善,有些常用方法(比如:去除字符串首尾空字符等功能)还是没有,使用起来不是很方便,这个时候可以选择使用boost中的相应函数。

你可能感兴趣的:(C++,c++,开发语言,visualstudio)