c++ string

来源:互联网 发布:知之深爱之切经典 编辑:程序博客网 时间:2024/06/04 18:43

基本说明

  要想使用标准C++中string类,必须要包含#include<string>,而不是#include<string.h>(字符串处理函数),using std::string/using spacename std;
  string类是基于下述模版定义的:  

template<class charT,class traits = char_traits<charT>,class Allocator = allocator<charT>>class basic_string{...};

//traits参数是一个类,它定义了类型要被表示为字符串时,所必须具备的特征。
//Allocator参数是用于处理字符串内存分配的类型。
  有4种预定义的具体化

typedef basic_string<char> string;typedef basic_string<char16_t> u16string;typedef basic_string<char32_t> u32string;typedef basic_string<wchar_t> wstring;

常用函数

1)构造函数

string()string(const char * s)string(const char * s,size_type n)string(const string & str)...

2)string的特征描述

size_type size()const //返回当前字符串的大小 mystring.length()size_type length()const //返回当前字符串的长度 mystring.size()bool empty()const //当前字符串是否为空 mystring.empty()...

3)string类的赋值

string& assign(const char *s);//用c类型字符串s赋值string& assign(const char *s,size_type n);//用c字符串s开始的n个字符赋值string& operator=(const string &str);//把字符串s赋给当前字符串string& assign(const string &str,size_type pos,size_type n);//把字符串s中从pos开始的n个字符赋给当前字符串...

4)string类的插入函数

//insert()方法使得能够将string对象,字符串数组或几个字符插入到string对象中...数据将被插入到插入点前面string& insert(size_type pos,const char * s);string& insert(size_type pos,const char * s,size_type n);string& insert(size_type pos1,const string& str);string& insert(size_type pos1,const string& str,size_type pos2,size_type n);//在pos1位置插入str对象中pos2开始的前n个字符...

5)string类的替换函数

//replace()方法指定了要替换的字符串部分和用于替换的内容。可以使用初始位置和字符数目或迭代区间来指定要替换的部分。//替换内容可以是string对象、字符串数组、也可以是特定字符的多个实例。//用于替换的string对象和数组,可以通过指定特定部分或迭代器区间做进一步修改。string& replace(size_type pos,size_type n1,const char * s);//删除从pos1开始的n1个字符,然后在pos1处插入字符串sstring& replace(size_type pos,size_type n1,const char * s,size_types n2);//删除从pos1开始的n1个字符,然后在pos1处插入字符串s的前n2个字符string& replace(size_type pos1,size_type n1,const string& str);//删除从pos1开始的n1个字符,然后在pos1处插入str对象string& replace(size_type pos1,size_type n1,const string& str,size_type pos2,size_types n2);//删除从pos1开始的n1个字符,然后在pos1处插入str对象中从pos2开始的n2个字符...

6)string类的查找函数

//在字符串中搜索给的子字符串或字符的位置。string::npos是字符串可存储的最大字符数,通常是无符号int或无符号long的最大取值size_type find(char c,int pos = 0)const;size_type find(const char * s,size_type pos=0)const;size_type find(const char * s,size_type_pos pos=0,size_types n)const;//查找s的前n个字符组成的子字符串size_type find(const string & str,size_type pos = 0)const;//从字符串的pos位置开始,查找子字符串str。如果找到,则返回该子字符串首次出现时其首字符的索引;否则,返回string::npos...

7)string类的连接函数

operator+=()//string对象、字符串数组、单个字符追加到string对象的后面string& append(const char * s);string& append(const char * s,size_type n);//字符串s的前n个字符string& append(const string& str);string& append(const string& str,size_type pos,size_type n);//指定初始位置和追加的字符数...

8)string类的存取函数

const char* c_str()const //mystring.c_str()方法返回一个指向c-风格字符串的指针operator[]()方法使得能够使用数组表示法来访问字符串的元素//mystring[0] 执行速度at()方法提供了相似的访问功能,只是索引是通过函数参数提供的//mystring.at(0) 安全性string substr(size_type pos = 0,size_type n = npos) const;//返回pos开始的n个字符组成的字符串
0 0
原创粉丝点击