string 的构造函数

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 a string 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 position pos and takes up to n characters (it takes less than n if the end of str 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


 

 


 

 

 

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值