C++ String类

今天看了一篇别人的博客介绍string的,特别全面,自己选了个别函数运行了一下,加深对其函数的理解。如果想要了解更多,参考:http://www.cnblogs.com/xFreedom/archive/2011/05/16/2048037.html

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
void test()
{
	/*-------------------string构造函数-------------------*/
	/*  string(const char *s);    //用字符串s初始化
	    string(int n,char c);     //用n个字符c初始化 */
	
	string ss("visual");  //调用构造函数
	string sss;           //调用默认构造函数
	string s = "visual";  // 调用复制构造函数
	/*------------------string的特性描述-------------------*/
	cout << "最大长度:  "<<s.max_size() << endl;      //返回string对象中可存放的最大字符串的长度
	cout << "s的大小:" << s.size() << endl;          //返回当前字符串的大小
	cout << "s的长度 =  " << s.length() << endl;      //返回当前字符串的长度
	cout << "s.at(2) = "<<s.at(2) << endl;            //返回第n个位置的字符
	cout << "s是否为空= " << s.empty() << endl;       //当前字符串是否为空
	cout << "s的容量 = " << s.capacity() << endl;      //返回当前容量(即string中不必增加内存即可存放的元素个数)

       /*------------------string类的输入输出操作----------------------*/
	cout << " s.assign(st) = " << s.assign("hello") << endl;      //把字符串st赋给当前字符串
	cout << "s.assign(st,n) = " << s.assign("OK",2) << endl;      //把st赋给s的第n个位置起
	cout << "s.operator=(st) = " << s.operator= ("hello") << endl; //把字符串st赋给当前字符串
	
	/*-----------------string的连接---------------------------------*/

	cout << "s.append(st) = " << s.append("studio") << endl;    //把char类型字符串s连接到当前字符串结尾 
	cout << "s.append(st,n) = " << s.append("2015",2) << endl;  //把c类型字符串s的前n个字符连接到当前字符串结尾
	cout << "s.operator+= " << s.operator+= ("hello") << endl;  //把字符串s连接到当前字符串的结尾
	
	/*--------------------string的比较-------------------------------*/
	cout << "s.compare(st) = " << s.compare("A") << endl;       //比较当前字符串和st的大小
	//compare函数在>时返回1,<时返回-1,==时返回0
}
int main()
{
	test();
	system("pause");
	return 0;
}
运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值