The string class

  • You must add this at the head of you code
# include <string>
  • Define variable of string like other types
string str;
  • Initialize it with string constant
string str = “hello”;
  • Read/Write string with cin/cout
cin >> str;
cout << str;

Assignment

Concatenation

Constructors

string (const char *cp, int len); string (const string& s2, int pos); string (const string& s2 ,int pos, int len);

Sub-string

substr (int pos, int len);

Modification

assin()

  • assign(const string& s): 用另一个字符串 s 的内容来赋值。
  • assign(const char* c_str): 用一个 C 风格的字符串(字符数组)来赋值。
  • assign(int count, char c): 用 count 个字符 c 来赋值。

insert()

  • insert(int pos, const string& s): 在索引位置 pos 处,插入字符串 s
  • insert(int pos, const char* c_str): 在索引位置 pos 处,插入 C 风格字符串 c_str
  • insert(int pos, int count, char c): 在索引位置 pos 处,插入 count 个字符 c

erase()

  • erase(int pos, int count): 从索引 pos 开始,删除 count 个字符。
  • erase(int pos): 从索引 pos 开始,删除到字符串末尾的所有字符。

append()

  • append(const string& s): 在末尾追加另一个字符串 s
  • append(const char* c_str): 在末尾追加一个 C 风格的字符串。
  • append(int count, char c): 在末尾追加 count 个字符 c

replace()

  • replace(int pos, int len, const string& s): 从索引 pos 开始,将长度为 len 的子串替换为字符串 s
  • replace(int pos, int len, const char* c_str): 替换为 C 风格字符串。
  • replace(int pos, int len, int count, char c): 替换为 count 个字符 c

Search

find (const string &s);

File I/O

 
Loading...