string类

2019-01-05  本文已影响0人  zhaoQiang012

string

1. string类常用方法

int capacity() const;  // 返回当前容量
int max_size() const;  // 返回string对象可存放最大长度
int size() const;  // 返回当前字符串大小
int length() const;  // 当前字符串长度
bool empty() const;  // 当前字符串是否为空
void resize(int len, char c);  // 置字符串大小为len,多去少补,不够用c补

2. string类常用方法2

string& insert(int p, string& s);  // 在p位置插入字符串s
string& replace(int p, int n, const char* s);  // 删除从p开始的n个字符,然后在p处插入s。
string& erase(int p, int n);  // 删除从p开始的n个字符,返回删除后的字符串
string substr(int pos=0, int n = npos) const;  // 返回pos开始的n个字符组成的字符串。
void swap(string& s2);  // 交换当前字符串与s2的值。
string& append(const char* s);  // 把字符串s连接到当前字符串的结尾。
void push_back(char c);  // 当前字符串尾部添加c。
const char* data() const;  // 返回一个以非null结尾的c字符数组。
const char* c_str() const;  // 返回一个以null结尾的c字符数组。

3. string类的查找

size_type find(const basic_string &str, size_type index);  // 返回str在字符串中第一次出现的位置,从index处开始查找,若没找到则返回string::npos。
size_type find(const char* str, size_type index);
size_type find(const char* str, size_type index, size_type length);
size_type find(char ch, size_type index);

4. 记录两个C++切片字符串的方法

void splitString(const string& s, vector<string>& v, const string& c)
{
  string::size_type pos1, pos2;
  pos1 = 0;
  pos2 = s.find(c);
  while (pos2 != string::npos) {
    v.push_back(s.substr(pos1, pos2-pos1));
    pos1 = pos2 + c.size();
    pos2 = s.find(c, pos1);
  }
  if (pos1 != s.length())
    v.push_back(s.substr(pos1));
}
string A;  // 待切片字符串
istringstream is(A);
string temp;
while (is >> temp) {
  ...
}
上一篇下一篇

猜你喜欢

热点阅读