zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    batch build OSG
    COM技术内幕第八章笔记组件复用
    在Fireworks CS5中使用PS滤镜
    不能载入ive场景
    转:lib,dll和h
    想不到的.ive
    显卡始终只支持OPENGL1.1
    初识3D JavaScript接口
    32位CPU寄存器简介以及TSS和TR
    3dsMax的Intervals
  • 原文地址:https://www.cnblogs.com/little-snake/p/4890613.html
Copyright © 2011-2022 走看看