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<char> string;

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

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

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

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

成员类型

member typedefinition
value_typechar
traits_typechar_traits<char>
allocator_typeallocator<char>
referencechar&
const_referenceconst char&
pointerchar*
const_pointerconst char*
iteratora random access iterator to char (convertible to const_iterator)
const_iteratora random access iterator to const char
reverse_iteratorreverse_iterator<iterator>
const_reverse_iteratorreverse_iterator<const_iterator>
difference_typeptrdiff_t
size_typesize_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 <class InputIterator> string (InputIterator first, InputIterator last);
initializer list (8)string (initializer_list<char> 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<char> il);
move (5)string& operator= (string&& str) noexcept;
  • 迭代器相关
函数函数原型功能描述
beginiterator begin() noexcept;Return iterator to beginning
const_iterator begin() const noexcept;
enditerator end() noexcept;Return iterator to end
const_iterator end() const noexcept;
rbeginreverse_iterator rbegin() noexcept;Return reverse iterator to reverse beginning
const_reverse_iterator rbegin() const noexcept;
rendreverse_iterator rend() noexcept;Return reverse iterator to reverse end
const_reverse_iterator rend() const noexcept;
cbeginconst_iterator cbegin() const noexcept;Return const_iterator to beginning
cendconst_iterator cend() const noexcept;Return const_iterator to end
crbeginconst_reverse_iterator crbegin() const noexcept;Return const_reverse_iterator to reverse beginning
crendconst_reverse_iterator crend() const noexcept;Return const_reverse_iterator to reverse end

 迭代器示例:

// string::begin/end
#include <iostream>
#include <string>
​
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
  • 容器大小或容量相关
函数函数原型功能描述
sizesize_t size() const noexcept;Return length of string
lengthsize_t length() const noexcept;Return length of string
max_sizesize_t max_size() const noexcept;Return maximum size of string
resizevoid resize (size_t n);Resize string
void resize (size_t n, const value_type& val);
capacitysize_t capacity() const noexcept;Return size of allocated storage
reservevoid reserve (size_t n = 0);Request a change in capacity
clearvoid clear() noexcept;Clear string
emptybool empty() const noexcept;Test if string is empty
shrink_to_fitvoid shrink_to_fit();Shrink to fit

  示例:

// resizing string
#include <iostream>
#include <string>
​
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 <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;
}
​
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;
atchar& at (size_t pos);获取字符串的字符
const char& at (size_t pos) const;
frontreference front();访问最后一个字符
const_reference front() const;
backchar& back();访问第一个字符
const char& back() const;

  成员访问示例:

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

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


Output:
Test string
------------------------------------------------------

// string::at
#include <iostream>
#include <string>
​​using namespace std;
int main ()
{
  std::string str ("Test string");
  for (unsigned i=0; i<str.length(); ++i)
  {
       cout << str.at(i)<<endl;
  }
  return 0;
}

Output:
Test string
------------------------------------------------------

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

// string::back
#include <iostream>
#include <string>
​
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<char> il);
appendstring& 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 <class InputIterator> string& append (InputIterator first, InputIterator last);
string& append (initializer_list<char> il);
push_backvoid push_back (char c);将字符追加到字符串
assignstring& 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 <class InputIterator> string& assign (InputIterator first, InputIterator last);
string& assign (initializer_list<char> il);
string& assign (string&& str) noexcept;
insertstring& 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 <class InputIterator> iterator insert (iterator p, InputIterator first, InputIterator last);
string& insert (const_iterator p, initializer_list<char> il);
erasestring& erase (size_t pos = 0, size_t len = npos);删除字符串中的字符
iterator erase (const_iterator p);
iterator erase (const_iterator first, const_iterator last);
replacestring& 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 <class InputIterator> string& replace (const_iterator i1, const_iterator i2, InputIterator first, InputIterator last);
string& replace (const_iterator i1, const_iterator i2, initializer_list<char> il);
swapvoid swap (string& str);交换字符串值
pop_backvoid pop_back();删除最后一个字符

  示例:

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

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

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

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

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

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

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

// string::pop_back
#include <iostream>
#include <string>
​
int main ()
{
  std::string str ("hello world!");
  str.pop_back();
  std::cout << str << '\n';
  return 0;
}
​
Output:
hello world
 
  • 字符串操作
函数函数原型功能描述
c_strconst char* c_str() const noexcept;Get C string equivalent
dataconst char* data() const noexcept;Get string data
get_allocatorallocator_type get_allocator() const noexcept;Get allocator
copysize_t copy (char* s, size_t len, size_t pos = 0) const;Copy sequence of characters from string
findsize_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;
rfindsize_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_ofsize_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_ofsize_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_ofsize_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_ofsize_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;
substrstring substr (size_t pos = 0, size_t len = npos) const;Generate substring
compareint 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;

成员常量
nposstatic 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 operatorsbool 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);
swapvoid 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
getlineistream& 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中的相应函数。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

摸鱼特长生.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值