string长度怎样判断

如题所述

string字符串的长度可以用string中的成员函数length()或者size()来判断。两者功能相同,返回值都是字符串长度。

编写下列程序为例,通过length函数和size函数得到字符串“Test string”的长度,运行结果如下:

扩展资料:

C++ 中的 string 类的用法:

1、string类的构造函数:

string(const char *s); //用c字符串s初始化 string(int n,char c); //用n个字符c初始化

此外,string类还支持默认构造函数和复制构造函数,如string s1;string s2="hello";都是正确的写法。当构造的string太长而无法表达时会抛出length_error异常 。

2、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为起始位置的字符数组中,返回实际拷贝的数目

温馨提示:答案为网友推荐,仅供参考
相似回答