c/c++ string

string类的定义、操作。

#include<iostream>
#include<string>
using namespace std;

int main()
{
	// 4 declare 
	string s1;			//default
	string s2( s1 );
	string s3( "hello" );
	string s4( 9, 's' );
	
	//read and write
	string s_1, s_2;
	cin>>s_1>>s_2;			//igore blank in head, find blank in tail will end;
	cout<<s_1<<endl;

	//读入未知数目的文本
	string word;
	while( cin>>word )		//read until end-of -file
	{
		cout<<word<<endl;
		if( word == "exit" )
		{
			cout<<"exit success"<<endl;
			break;
		}
	}

	//用getline读取整行文本,getline不会保存换行符
	string line;
	while( getline( cin, line ) )
	{
		cout<<line<<endl;
		if( line == "exit" )
		{
			cout<<"exit success"<<endl;
			break;
		}
	}

	//string.size() and string.empty
	string str_size;
	cout<<"test string size"<<endl;
	cin>>str_size;
	if( str_size.empty() )
		cout<<"string is empty"<<endl;
	else
		cout<<"string is not empty"<<endl;
	
	//配套类型string::size_type实现与及其无关;int 型变量容易出错,不便移植;unsigned 可用于string::size_type可用的地方。
	//关系操作符==、+=、<、<=、>、>=,使用字典顺序排序
	string big = "big", small = "small", substr = "hello",phrase = "hello world";		//substr 小于 phrase

	//string赋值,有效率上的问题
	string str1, str2 = "value assignment come with efficent problem";
	str1 = str2;

	//string对象相加
	str2 = "c plus plus";
	str1 = "hell";
	str2 += str1;

	//和字符串字面值的连接,必须用string类型作为左值
	str1 = str2 + "hello world" + "!!!";
	
	//下标操作string单个字符
	for( string::size_type ix = 0; ix != str1.size(); ix++ )
	{
		cout<< str1[ix] <<endl;
		str1[ix] = '*';
	}

	//下标值计算
	str1[2*1] = 'a';
	cout<<str1<<endl<<"下标计算"<<endl;
	
	//string中单个字符处理
	cout<<"单个字符的处理"<<endl;
	if( ispunct(str1[2]) )
		cout<<"str1[2] 是一个标点"<<endl;

	string s;
	cout<<s[0]<<endl;		//越界

	return 0;
}

操作单个字符时使用cctype定义的函数,满足条件则为true:

isalnum(c)  是字母或数字

isalpha(c)  是字母

iscntrl(c)  是控制字符

isdigit(c)  是数字

isgraph(c)  不是空格,可打印

islower(c)  小写字母

isprint(c)  可打印字符

ispunct(c)  标点符号

isspace(c)  空白字符

isupper(c)  大写字母

isxdigit(c)  十六进制数

tolower(c)  是大写字母时返回小写字母,否则返回c

toupper(c)  是小写字母时返回大写字母,否则返回c

posted @ 2015-10-18 22:49  little-snake  阅读(174)  评论(0编辑  收藏  举报