C string 类常用函数本文由 NaroAix 贡献 C++string 类常用函数 string 类的构造函数: string(const char *s); //用c 字符串 s 初始化 string(int n,char c); //用n 个字符 c 初始化此外, string 类还支持默认构造函数和复制构造函数,如 string s1; string s2="hello" ; 都是正确的写法。当构造的 string 太长而无法表达时会抛出 length_error 异常 string 类的字符操作: const char &operator[](int n)const; const char &at(int n)const; char &operator[](int n); char &at(int n); operator[] 和 at() 均返回当前字符串中第 n 个字符的位置, 但 at 函数提供范围检查, 当越界时会抛出 out_of_range 异常, 下标运算符[] 不提供检查访问。 const char *data()const;// 返回一个非 null 终止的 c 字符数组 const char *c_str()const;// 返回一个以 null 终止的 c 字符串 int copy(char *s, int n, int pos = 0) const;// 把当前串中以 pos 开始的 n 个字符拷贝到以 s 为起始位置的字符数组中, 返回实际拷贝的数目 string 的特性描述: int capacity()const; // 返回当前容量(即 string 中不必增加内存即可存放的元素个数) int max_size()const; // 返回 string 对象中可存放的最大字符串的长度 int size()const; // 返回当前字符串的大小 int length()const; // 返回当前字符串的长度 bool empty()const; // 当前字符串是否为空 void resize(int len,char c);// 把字符串当前大小置为 len , 并用字符 c 填充不足的部分 string 类的输入输出操作: string 类重载运算符 operator>> 用于输入,同样重载运算符 operator<< 用于输出操作。函数 getline(istream &in,string &s); 用于从输入流 in 中读取字符串到 s 中,以换行符'\n' 分开。 string 的赋值: string &operator=(const string &s);// 把字符串 s 赋给当前字符串 string &assign(const char *s);// 用c 类型字符串 s 赋值 string &assign(const char *s,int n);// 用c 字符串 s 开始的 n 个字符赋值 string &assign(const string &s);// 把字符串 s 赋给当前字符串 string &assign(int n,char c);// 用n 个字符 c 赋值给当前字符串 string &assign(const string &s,int start,int n);
C string类常用函数 来自淘豆网m.daumloan.com转载请标明出处.