c++ string

简介

  在c++中要使用string类需包含头文件:#include <string>.

常用函数介绍

1. string.length()

说明:

  用来返回string类型字符串的长度。  

 2. getline()

定义:

  c++11

(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。在(1)中,可以自定义结束字符 delim;在(2)中,默认的结束字符为 ' '。getline()函数常用来读入包含空格的字符串。

 3. string.begin() 和 string.end()

说明:

  begin()函数,返回一个迭代器,指向字符串的第一个元素。end()函数,也是返回一个迭代器,指向字符串末尾(最后一个字符的后一个位置)。

例如:

string str = "What";
cout << "str.begin(): " << *(str.begin()) << endl;
cout << "str.end(): " << *(str.end()-1) <<endl;

------------------------------------------------------

  str.begin(): W
  str.end(): t

  

 4. string.find()

定义:

  c++11

//str为需要查找的字符串,pos为开始查找的位置

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;

说明:

常用于c++中字符串匹配字符或子字符串,如果匹配成功,则返回The position of the first character of the first match,If no matches were found, the function returns string::npos。其中string::npos为常量,定义为值-1,由于size_t是无符号整数类型,因此它是此类型的最大可表示值。

 5. string.erase()

定义:

注意参数和返回值

sequence (1)  //删除从索引pos开始, 长度为len的字符串   
string& erase (size_t pos = 0, size_t len = npos);
character (
2) //删除迭代器 p 指向的字符 iterator erase (const_iterator p);
range (
3) //删除从迭代器first和last之间的字符 iterator erase (const_iterator first, const_iterator last);

说明:

用于对字符串中的字符或子字符串进行删除。

原文地址:https://www.cnblogs.com/huwt/p/10591353.html