string 的构造函数

来源:互联网 发布:ios版狂野飙车同步数据 编辑:程序博客网 时间:2024/05/21 00:54

1. string ( const char * s );

 

Content is initialized to a copy of the string formed by the null-terminated character sequence (C string) pointed bys. The length of the character sequence is determined by the first occurrence of a null character (as determined bytraits.length(s)). This version can be used to initialize astring object using astring literal constant.

sting 内容是指针*s指向的c类型的字符串。string 的长度由字符串的长度决定。例如下例中tmp.size()=7; 即:size为string包含的字符个数,并不包括终止符。

int main(){string tmp("abcdefg");cout<<tmp<<endl;getchar();}

2. string ( const char * s, size_t n );

Content is initialized to a copy of the string formed by the first n characters in the array of characters pointed bys.

 

string 的内容是指针s指向的字符串中前n位。如:

int main(){string tmp("abcded0. fg",3);cout<<tmp<<endl;getchar();}

输出为:abc

如果n的数值大于s字符串的长度,则将s的内容全部copy到tmp中,并且tmp.size()=n。初始化时分配了n个空间,但是多出来的空间并不确定放了什么。有待调查~~

例如:

int main(){string tmp("abcded0. fg",20);cout<<tmp<<endl;cout<<tmp.size()<<endl;getchar();}


输出为:

abcded0. fg

20

3.string ( size_t n, char c );

Content is initialized as a string formed by a repetition of character c,n times.

string 的内容是n个c字符。

例如:

int main(){string tmp(10,'m');cout<<tmp<<endl;cout<<tmp.size()<<endl;getchar();}

输出为:

mmmmmmmmmm

10
注:string tmp(10,'m'); 此处'm'不缺少单引号,否则认为m是一个未声明的变量,而不是个字符。也不可用双引号,双引号意为包含内容为字符串。

4.string ( const string& str );

Content is initialized to a copy of the string object str.

复制构造函数。

例如:

int main(){string tmp("abcdefg");cout<<tmp<<endl;string test(tmp);cout<<test<<endl;getchar();}


输出为:

abcdefg

abcdefg

5.string ( const string& str, size_t pos, size_t n = npos );

Content is initialized to a copy of a substring of str. The substring is the portion ofstr that begins at the character positionpos and takes up to n characters (it takes less than n if the end ofstr is reached before).

new string复制str 的字符,内容为从位置pos开始n个字符为止。入果从pos位置到结尾字符数少于n,则到n为止。

例如:

int main(){string tmp("abcdefg");string test(tmp,1,15);cout<<tmp<<endl;cout<<test<<endl;cout<<test.size()<<endl;getchar();}

n大于从位置1 到末尾的字符数,故实际情况中,字符串复制到末尾。size为实际字符数。

输出为:

abcdefg

bcdefg