c++ string 字符串构造初始化

创建日期: 2024-11-19 14:42 | 作者: 风波 | 浏览次数: 16 | 分类: C++

来源:https://cplusplus.com/reference/string/string/string/

序号 函数声明
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;

Construct string object

Constructs a string object, initializing its value depending on the constructor version used:

All constructors above support an object of member type allocator_type as additional optional argument at the end, which for string is not relevant (not shown above, see basic_string's constructor for full signatures).

Parameters

size_t is an unsigned integral type.

Example

// string constructor
#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");
  std::string s5 ("Another character sequence", 12);
  std::string s6a (10, 'x');
  std::string s6b (10, 42);      // 42 is the ASCII code for '*'
  std::string s7 (s0.begin(), s0.begin()+7);

  std::cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3;
  std::cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6a: " << s6a;
  std::cout << "\ns6b: " << s6b << "\ns7: " << s7 << '\n';
  return 0;
}

Output:

s1: 
s2: Initial string
s3: str
s4: A character sequence
s5: Another char
s6a: xxxxxxxxxx
s6b: **********
s7: Initial
16 浏览
10 爬虫
0 评论