C++ String类总结

头文件

#include <string>

构造函数

default (1)
basic_string();explicit basic_string (const allocator_type& alloc);
copy (2)
basic_string (const basic_string& str);basic_string (const basic_string& str, const allocator_type& alloc);
substring (3)
basic_string (const basic_string& str, size_type pos, size_type len = npos,              const allocator_type& alloc = allocator_type());
from c-string (4)
basic_string (const charT* s, const allocator_type& alloc = allocator_type());
from buffer (5)
basic_string (const charT* s, size_type n,              const allocator_type& alloc = allocator_type());
fill (6)
basic_string (size_type n, charT c,              const allocator_type& alloc = allocator_type());
range (7)
template <class InputIterator>  basic_string  (InputIterator first, InputIterator last,                 const allocator_type& alloc = allocator_type());
initializer list (8)
basic_string (initializer_list<charT> il,              const allocator_type& alloc = allocator_type());
move (9)
basic_string (basic_string&& str) noexcept;basic_string (basic_string&& str, const allocator_type& alloc);

Construct basic_string object

(1) empty string constructor (default constructor)
构造一个空字符串,长度为0个字符。
(2) copy constructors
构造str的副本。
(3) substring constructor
复制str中从字符位置pos开始并跨越len个字符的部分(如果str太短或len为basic_string::npos,则复制到str的末尾)。
(4) from c-string
复制s指向的以空结束的字符序列(C-string)。
长度通过调用traits_type::length(s)来确定。
(5) from buffer
从s指向的字符数组中复制前n个字符。
(6) fill constructor
用字符c的n个连续副本填充字符串。
(7) range constructor
以相同的顺序复制范围[第一个,最后一个)中的字符序列。
(8) initializer list
以相同的顺序复制il中的每个字符。
(9) move contructors
获取str的内容。
STR处于未指定但有效的状态。

参数

alloc

分配器对象。
容器保存并使用该分配器的内部副本。
成员类型allocator_type是容器使用的内部分配器类型,在basic_string中定义为其第三个模板形参(Alloc)的别名。
如果allocator_type是默认分配器的实例化(它没有状态),这是不相关的。

str

另一个相同类型的basic_string对象(具有相同的类模板参数charT, traits和Alloc),其值要么被复制要么被获取

pos

作为子字符串复制到对象的str中第一个字符的位置。
如果这个值大于str的长度,则抛出out_of_range。
注意:str中的第一个字符是0(不是1)。

len

要复制的子字符串的长度(如果字符串较短,则复制尽可能多的字符)。
basic_string::npos的值表示str结束前的所有字符。

s

要复制的字符数。

n

用于填充字符串的字符。字符串中的n个字符都将初始化为该值的副本

c

将迭代器输入到范围内的初始位置和最终位置。使用的范围是[first,last),它包括第一个和最后一个之间的所有字符,包括第一个指向的字符,但不包括最后一个指向的字符。
函数模板参数InputIterator应该是一个输入迭代器类型,它指向可转换为charT类型的元素。
如果InputIterator是整型,则参数被转换为适当的类型,以便使用signature(5)。

il

initializer_list对象。
这些对象是从初始化列表声明器自动构造的。

示例

#include <iostream>
#include <string>

int main ()
{
  std::string s0 ("Initial string");

  // constructors used in the same order as described above:
  std::string s1;
  std::string s2 (s0);
  std::string s3 (s0, 8, 3);
  std::string s4 ("A character sequence", 6);
  std::string s5 ("Another character sequence");
  std::string s6 (10, 'x');
  std::string s7a (10, 42);
  std::string s7b (s0.begin(), s0.begin()+7);

  std::cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3;
  std::cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6: " << s6;
  std::cout << "\ns7a: " << s7a << "\ns7b: " << s7b << '\n';
  return 0;
}

 Output:

s1: 
s2: Initial string
s3: str
s4: A char
s5: Another character sequence
s6: xxxxxxxxxx
s7a: **********
s7b: Initial

成员

begin

返回指向字符串第一个字符的迭代器。

示例

// 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 << *it;
  std::cout << '\n';

  return 0;
}

end

返回指向字符串结束后字符的迭代器。
结束后字符是一个理论字符,它跟在字符串的最后一个字符之后。不应取消引用。
由于标准库函数使用的范围不包括其结束迭代器所指向的元素,因此此函数通常与basic_string::begin组合使用,以指定包含字符串中所有字符的范围。
如果对象是空字符串,此函数返回与basic_string::begin相同的值。

示例

// 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 << *it;
  std::cout << '\n';

  return 0;
}

rbegin

返回一个反向迭代器,指向字符串的最后一个字符(即它的反向开头)。
反向迭代器向后迭代:增加它们会将它们移动到字符串的开头。
Rbegin指向成员end将要指向的字符之前的字符。

示例

// string::rbegin/rend
#include <iostream>
#include <string>

int main ()
{
  std::string str ("now step live...");
  for (std::string::reverse_iterator rit=str.rbegin(); rit!=str.rend(); ++rit)
    std::cout << *rit;
  return 0;
}
输出
...evil pets won

rend

返回反向迭代器
返回一个反向迭代器,指向字符串第一个字符之前的理论元素(被认为是它的反向结尾)。
basic_string::rbegin和basic_string::rend之间的范围包含了basic_string的所有字符(倒序)。

示例

// string::rbegin/rend
#include <iostream>
#include <string>

int main ()
{
  std::string str ("now step live...");
  for (std::string::reverse_iterator rit=str.rbegin(); rit!=str.rend(); ++rit)
    std::cout << *rit;
  return 0;
}

cbegin

返回指向字符串第一个字符的const_iterator。
const_iterator是指向const内容的迭代器。这个迭代器可以增加或减少(除非它本身也是const),就像basic_string::begin返回的迭代器一样,但它不能用来修改它所指向的内容,即使basic_string对象本身不是const。

示例

// string::cbegin/cend
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Lorem ipsum");
  for (auto it=str.cbegin(); it!=str.cend(); ++it)
    std::cout << *it;
  std::cout << '\n';

  return 0;
}

crbegin

Return const_reverse_iterator to reverse beginning

Returns a const_reverse_iterator pointing to the last character of the string (i.e., its reverse beginning).

示例

// string::crbegin/crend
#include <iostream>
#include <string>

int main ()
{
  std::string str ("lorem ipsum");
  for (auto rit=str.crbegin(); rit!=str.crend(); ++rit)
    std::cout << *rit;
  std::cout << '\n';

  return 0;
}

 crend

 返回一个const_reverse_iterator,指向字符串第一个字符之前的理论字符(被认为是它的反向结尾)。

示例

// string::crbegin/crend
#include <iostream>
#include <string>

int main ()
{
  std::string str ("lorem ipsum");
  for (auto rit=str.crbegin(); rit!=str.crend(); ++rit)
    std::cout << *rit;
  std::cout << '\n';

  return 0;
}

size

返回以字符数表示的字符串长度。
这是符合basic_string内容的实际字符数,不一定等于它的存储容量。
basic_string::size和basic_string::length都是同义词,返回相同的值。

示例

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

int main ()
{
  std::string str ("Test string");
  std::cout << "The size of str is " << str.size() << " characters.\n";
  return 0;
}

 length

 返回以字符数表示的字符串长度。
这是符合basic_string内容的实际字符数,不一定等于它的存储容量。
basic_string::size和basic_string::length都是同义词,返回相同的值。

示例

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

int main ()
{
  std::string str ("Test string");
  std::cout << "The size of str is " << str.length() << " characters.\n";
  return 0;
}

max_size

返回basic_string可以达到的最大长度。
由于已知的系统或库实现限制,这是字符串可以达到的最大潜在长度,但不能保证对象能够达到该长度:在达到该长度之前,它仍然可能无法分配存储空间。

示例

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

 resize

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

示例

// resizing string
#include <iostream>
#include <string>

int main ()
{
  std::string str ("I like to code in C");
  std::cout << str << '\n';

  std::string::size_type sz = str.size();

  str.resize (sz+2,'+');
  std::cout << str << '\n';

  str.resize (14);
  std::cout << str << '\n';
  return 0;
}

capacity

 返回当前为basic_string分配的存储空间大小,以字符表示。
这个容量不一定等于字符串长度。它可以等于或更大,额外的空间允许对象在向basic_string添加新字符时优化其操作。
注意,这个容量并没有限制basic_string的长度。当这个容量耗尽而需要更多时,对象会自动扩展它(重新分配它的存储空间)。basic_string长度的理论限制由成员max_size给出。

basic_string的容量可以在对象被修改的任何时候被修改,即使这种修改意味着大小的减小或者容量没有被耗尽(这与vector容器中容量的保证相反)。

basic_string的容量可以通过调用成员reserve显式地改变。

示例

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

reserve

请求将字符串容量调整为计划的大小更改为最多n个字符的长度。
如果n大于当前字符串容量,该函数会导致容器将其容量增加到n个字符(或更大)。
在所有其他情况下,它被视为一个非绑定请求,以缩小字符串容量:容器实现可以自由优化,并让basic_string的容量大于n。
此函数对字符串长度没有影响,也不能改变其内容。

示例

// string::reserve
#include <iostream>
#include <fstream>
#include <string>

int main ()
{
  std::string str;

  std::ifstream file ("test.txt",std::ios::in|std::ios::ate);
  if (file) {
    std::ifstream::streampos filesize = file.tellg();
    str.reserve(filesize);

    file.seekg(0);
    while (!file.eof())
    {
      str += file.get();
    }
    std::cout << str;
  }
  return 0;
}

clear

擦除basic_string的内容,使其成为一个空字符串(长度为0个字符)。

 示例

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

int main ()
{
  char c;
  std::string str;
  std::cout << "Please type some lines of text. Enter a dot (.) to finish:\n";
  do {
    c = std::cin.get();
    str += c;
    if (c=='\n')
    {
       std::cout << str;
       str.clear();
    }
  } while (c!='.');
  return 0;
}

 empty

返回basic_string是否为空(即它的长度是否为0)。
这个函数不会以任何方式修改字符串的值。要清除basic_string的内容,请参见basic_string::clear。

示例

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

shrink_to_fit

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

示例

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

int main ()
{
  std::string str (100,'x');
  std::cout << "1. capacity of str: " << str.capacity() << '\n';

  str.resize(10);
  std::cout << "2. capacity of str: " << str.capacity() << '\n';

  str.shrink_to_fit();
  std::cout << "3. capacity of str: " << str.capacity() << '\n';

  return 0;
}

operator[]

返回对basic_string中pos位置字符的引用

示例

// string::operator[]
#include <iostream>
#include <string>

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

at

返回对basic_string中pos位置字符的引用。
该函数自动检查pos是否是字符串中某个字符的有效位置(即pos是否小于字符串长度),如果不是则抛出out_of_range异常。

示例

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

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

back

返回对basic_string的最后一个字符的引用。
此函数不能在空字符串上调用。

示例

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

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

front

返回对basic_string的第一个字符的引用。
与成员basic_string::begin返回相同字符的迭代器不同,该函数返回一个直接引用。
此函数不能在空字符串上调用。

示例

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

int main ()
{
  std::string str ("test string");
  str.front() = 'T';
  std::cout << str << '\n';
  return 0;
}

operator+=

扩展basic_string,在其当前值的末尾附加额外字符:
(有关其他附加选项,请参阅成员函数append)。

示例

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

append

扩展basic_string,在其当前值的末尾附加额外字符:

1)string


追加str的副本。
(2)substring
附加str的子字符串的副本。子字符串是str的一部分,从字符位置subpos开始并跨越子字符(或者直到str的末尾,如果str太短或subblen为basic_string::npos)。
(3) c-string
附加由s指向的以空结束的字符序列(C-string)组成的字符串的副本。
这个字符序列的长度由调用traits_type::length(s)决定。
(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;
}

push_back

将字符c追加到basic_string的末尾,将其长度增加1。

示例

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

assign

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

(1) string

str副本。

(2) substring

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

(3) c-string

复制s指向的以空结束的字符序列(C-string)。
长度通过调用traits_type::length(s)来确定

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

insert

译文:

在basic_string中插入额外的字符,就在pos(或p)表示的字符之前:


(1) string
插入str的副本。
(2) substring
插入str的子字符串的副本。子字符串是str的一部分,从字符位置subpos开始并跨越子字符(或者直到str的末尾,如果str太短或如果sublen为npos)。
(3) c-string
插入由s指向的以空结束的字符序列(C-string)组成的字符串的副本。
这个字符序列的长度由调用traits_type::length(s)决定。

(4) buffer

在s指向的字符数组中插入前n个字符的副本。
(5) fill
插入字符c的n个连续副本。
(5) fill
插入字符c。
(7) range
以相同的顺序插入范围[第一个,最后一个)中的字符序列的副本。
(8) initializer list
以相同的顺序插入il中每个字符的副本。

示例

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

erase

删除部分basic_string,减少其长度:
(1) sequence
擦除字符串值中从字符位置pos开始并跨越len字符的部分(如果内容太短或len为basic_string::npos,则直到字符串结束)。
注意,默认参数清除字符串中的所有字符(如成员函数clear)。
(2)字符
擦除由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;
}

replace

用新内容替换字符串中以pos开头并跨度为len字符的部分(或在[i1,i2)范围内的部分):

示例

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

swap

通过str的内容交换容器的内容,str是另一个相同类型的basic_string对象。长度可能不同。
在调用该成员函数之后,该对象的值是调用之前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;
}

pop_back

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

示例

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

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

c_str

返回一个指向数组的指针,该数组包含以空结束的字符序列(即C-string),表示basic_string对象的当前值。
该数组包含构成basic_string对象值的相同字符序列,并在末尾加上一个额外的终止空字符(charT())。

示例

// 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 = strtok(NULL," ");
  }

  delete[] cstr;
  return 0;
}

data

返回的指针可以通过进一步调用修改该对象的其他成员函数而失效

示例

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

get_allocator

返回与basic_string关联的allocator对象的副本。

copy

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

示例

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

find

在basic_string中搜索由其参数指定的序列的第一次出现。
当指定pos时,搜索只包括位于pos位置或之后的字符,忽略任何可能出现的包括pos位置之前的字符。
该函数使用traits_type::eq来确定字符等价性。
注意,与成员find_first_of不同,只要搜索多个字符,只匹配其中一个字符是不够的,整个序列必须匹配。

示例

// string::find
#include <iostream>
#include <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::string::size_type 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;
}

rfind

在basic_string中搜索由其参数指定的序列的最后一次出现。
当指定pos时,搜索只包括从pos位置开始或之前开始的字符序列,忽略从pos位置开始的任何可能匹配。
该函数使用traits_type::eq来确定字符等价性。

示例

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

int main ()
{
  std::string str ("The sixth sick sheik's sixth sheep's sick.");
  std::string key ("sixth");

  std::string::size_type found = str.rfind(key);
  if (found!=std::string::npos)
    str.replace (found,key.length(),"seventh");

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

  return 0;
}

find_first_of

在basic_string中搜索与参数中指定的任何字符匹配的第一个字符。
当指定pos时,搜索只包括位于pos位置或之后的字符,忽略pos之前的任何可能出现的字符。
注意,序列中的一个字符匹配就足够了(不是所有字符)。有关匹配整个序列的函数,请参阅basic_string::find。
该函数使用traits_type::eq来确定字符等价性。

示例

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

int main ()
{
  std::string str ("PLease, replace the vowels in this sentence by asterisks.");
  std::string::size_type 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;
}

find_last_of

在basic_string中搜索与参数中指定的任何字符匹配的最后一个字符。
当指定pos时,搜索只包括位于pos位置或之前的字符,忽略pos位置之后的任何可能出现的字符。
该函数使用traits_type::eq来确定字符等价性。

示例

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

void SplitFilename (const std::string& str)
{
  std::cout << "Splitting: " << str << '\n';
  std::string::size_type 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;
}

find_first_not_of

查找字符串中不匹配的字符

在basic_string中搜索与参数中指定的任何字符不匹配的第一个字符。
当指定pos时,搜索只包括位于pos位置或之后的字符,忽略该字符之前的任何可能出现的字符。
该函数使用traits_type::eq来确定字符等价性。

示例

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

int main ()
{
  std::string str ("look for non-alphabetic characters...");

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

find_last_not_of

从末尾开始查找字符串中不匹配的字符
在basic_string中搜索不匹配其参数中指定的任何字符的最后一个字符。
当指定pos时,搜索只包括位于pos位置或之前的字符,忽略pos位置之后的任何可能出现的字符。
该函数使用traits_type::eq来确定字符等价性。\

示例

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

int main ()
{
  std::string str ("Please, erase trailing white-spaces   \n");
  std::string whitespaces (" \t\f\v\n\r");

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

substr

返回一个新构造的basic_string对象,其值初始化为该对象的子字符串的副本。
子字符串是对象的一部分,从字符位置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 (12,12);         // "generalities"

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

compare

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

示例

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

npos

Npos是一个静态成员常量值,对于成员类型为size_type的元素具有最大的可能值。
这个值,当用作basic_string成员函数中的len(或subblen)形参时,表示“直到字符串结束”。
作为返回值,它通常用于表示不匹配。
该常量的定义值为-1,因为成员类型size_type是一个无符号整型,所以它是该类型可能表示的最大值。

string转char

调用strcpy函数

    string s="123456"; 
    char c[s.length()]; 
	
	/*
	**调用strcpy函数,和字符串的data函数 
	**1、strcpy不能赋值给char指针 ,只能赋值给char数组 
	**2、char数组长度,必须大于等于string长度 
	*/ 
	strcpy(c,s.data()); 
    c[0]='6';

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值