string 类与字符串流处理

本文通过一个C++示例程序详细介绍了如何使用STL库中的string类进行字符串赋值、连接、修改及子串分析等操作。此外还展示了字符串交换、查找等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// fig19_01.cpp
// demonstrating string assignment and concatenation

#include <iostream>
#include <string>             // 完全不同于string.h  可以include文件下找到
//#include <string.h>

//  应注意string.h 中字符处理函数的区别

using namespace std;    // 采取标准命名空间   iostream 不同于 iostream.h

//  全部函数可以在basic_string中查找 MSDN
int main()
{
	string s1( "cat" ), s2, s3;

	s2 = s1;
	s3.assign( s1 );
	cout<< "s1:" << s1 << "\ns2:" << s2 << "\ns3:" << s3 << endl;

	// modify s2 and s3
	s2[0] = s3[2] = 'r';

	cout<< "After modification of s2 and s3:\n"
		<< "s1:" << s1 << "\ns2:" << s2 << "\ns3:" << s3 << endl;

	// demostrating member function at()
	int len = s3.length();
	for( int x=0; x<len; ++x )
		cout<< s3.at( x );

	// concatenation
	string s4( s1 + "apult" ), s5;

	//overloaded +=
	s3 += "pet";
	s1.append( "acomb" );

	s5.append( s1, 4, s1.size() );

	cout<< "\n After concatcenation:\n"
		<< "s1:" << s1 << "\ns2:" << s2 << "\ns3:" << s3
		<< "\ns4:" << s4 << "\ns5:" << s5 <<endl;

	//////////   子串分析     ///////////////

	string s6( " The airplane flew away." );
	cout<< s6.substr( 7,5 ) << endl;        // 从第7个开始读取5个

	//        ********* 交换 ************  //

	string first( "one" ), second( "two" );
	cout<< "Before swap:\n first: " << first
		<< "\n second: " << second << endl;
	first.swap( second );
	cout<< "After swap:\n first: " << first
		<< "\n second: " << second << endl;

	// length or size 表示目前string 的大小或长度,是目前存放的字符数
	// capacity 是不必增加内存即可存放的总的元素个数
	// max_size 是最多能放多少
	// find( "subtree" ) 是从头开始找subtree,找到返回下标
	// rfind 为从后往回找
	// find_first_ of 第一次找到
	// find_last_of
	// find_fist_not_of( "abcd" ) 打到第一个不在"abcd"中的字符的下标,从头找
	// find_last_not_of  从尾找
	// replace insert compare参见 basic_string
	// < > = >= <= != 等都有重载,参见basic_string


	return 0;
}

转载于:https://my.oschina.net/delmore/blog/4777

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值