C++学习系列(四)——String使用

来源:互联网 发布:防范和打击电信网络 编辑:程序博客网 时间:2024/06/06 19:35

参考链接:https://www.cnblogs.com/rosesmall/archive/2012/03/28/2422373.html

1.string使用
string 并不是一个单独的容器,只是basic_string模板类的一个typedef而已,相应的还有wstring。
string相当于一个保存字符的序列容器,因此除了有字符串的一些常用操作以外,还有包含了所有的序列容器的操作。字符串的常用操作包括:增加、删除、修改、查找比较、链接、输入、输出等。

1.1 充分使用string 操作符
string 重载了许多操作符,包括 +, +=, <, =, , [], <<, >>等,正式这些操作符,对字符串操作非常方便。先看看下面这个例子:tt.cpp(例程2)

#i nclude <string>#i nclude <iostream>using namespace std;int main(){string strinfo="Please input your name:";cout << strinfo ;cin >> strinfo;if( strinfo == "winter" )cout << "you are winter!"<<endl;else if( strinfo != "wende" )cout << "you are not wende!"<<endl;else if( strinfo < "winter")cout << "your name should be ahead of winter"<<endl;elsecout << "your name should be after of winter"<<endl;strinfo += " , Welcome to China!";cout << strinfo<<endl;cout <<"Your name is :"<<endl;string strtmp = "How are you? " + strinfo;for(int i = 0 ; i < strtmp.size(); i ++)cout<<strtmp[i];return 0;}

下面是程序的输出

-bash-2.05b$ make ttc++ -O -pipe -march=pentiumpro tt.cpp -o tt-bash-2.05b$ ./ttPlease input your name:Heroyou are not wende!Hero , Welcome to China!How are you? Hero , Welcome to China!

有了这些操作符,在STL中仿函数都可以直接使用string作为参数,例如 less, great, equal_to 等,因此在把string作为参数传递的时候,它的使用和int 或者float等已经没有什么区别了。例如,你可以

map<string, int> mymap;//以上默认使用了less<string>

operator + 以后,你可以直接连加,例如:

string strinfo="Winter";string strlast="Hello " + strinfo + "!";//你还可以这样:string strtest="Hello " + strinfo + " Welcome" + " to China" + " !";

看见其中的特点了吗?只要你的等式里面有一个 string 对象,你就可以一直连续”+”,但有一点需要保证的是,在开始的两项中,必须有一项是 string 对象。其原理很简单:

系统遇到”+”号,发现有一项是string 对象。
系统把另一项转化为一个临时 string 对象。
执行 operator + 操作,返回新的临时string 对象。
如果又发现”+”号,继续第一步操作。

由于这个等式是由左到右开始检测执行,如果开始两项都是const char* ,程序自己并没有定义两个const char* 的加法,编译的时候肯定就有问题了。

原创粉丝点击