string类

作者: zhaoQiang012 | 来源:发表于2019-01-05 23:50 被阅读0次

    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);
    
    • 判断字符串a是否包含字符串b,使用(a.find(b) != string::npos)

    • at(size_type index): 返回一个指向index处字符的引用,若不在字符串范围内,返回一个out_of_range异常。

    • size_type rfind(const basic_string& str, size_type index):返回最后一个与str中的某个字符匹配的字符,从index开始查找。如果没找到就返回string::npos。

    • size_type find_first_of(const basic_string& str, size_type index=0):查找在字符串中第一个与str中的某个字符匹配的字符,返回它的位置。搜索从index开始,如果没找到就返回string::npos。

    • size_type find_first_not_of(const basic_string& str, size_type index=0):在字符串中查找第一个与str中的字符都不匹配的字符,返回它的位置。搜索从index开始。如果没找到就返回string::nops。

    • size_type find_last_of(const basic_string& str, size_type index=0):在字符串中查找最后一个与str中的某个字符匹配的字符,返回它的位置。搜索从index开始。如果没找到就返回string::nops。

    • size_type find_last_not_of(const basic_string& str, size_type index=0): 在字符串中查找最后一个与str中的字符都不匹配的字符,返回它的位置。搜索从index开始。如果没找到就返回string::nops。


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

    • (1)对单字符的切片
    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));
    }
    
    • (2) 对字符串中空格进行切片方法2
    string A;  // 待切片字符串
    istringstream is(A);
    string temp;
    while (is >> temp) {
      ...
    }
    

    相关文章

      网友评论

          本文标题:string类

          本文链接:https://www.haomeiwen.com/subject/flqjrqtx.html