详细解说STL string
0 前言: string 的角色
C++ 语言是个十分优秀的语言,但优秀并不表示完美。还是有许多人不愿意使用C或者C++,为什么?原因众多,其中之一就是C/C++的文本处理功能太麻烦,用起来很不方便。以前没有接触过其他语言时,每当别人这么说,我总是不屑一顾,认为他们根本就没有领会C++的精华,或者不太懂C++,现在我接触perl, php, 和Shell脚本以后,开始理解了以前为什么有人说C++文本处理不方便了。举例来说,如果文本格式是:
用户名 电话号码,
Tom 23245332
Jenny 22231231
Heny 22183942
Tom 23245332
...
文件名name.txt
现在我们需要对用户名排序,且只输出不同的姓名。
那么在shell 编程中,可以这样用: awk '{print $1}' name.txt | sort | uniq
如果使用C/C++ 就麻烦了,他需要做以下工作:
- 先打开文件,检测文件是否打开,如果失败,则退出。
- 声明一个足够大得二维字符数组或者一个字符指针数组
- 读入一行到字符空间
- 然后分析一行的结构,找到空格,存入字符数组中。
- 关闭文件
- 写一个排序函数,或者使用写一个比较函数,使用qsort排序
- 遍历数组,比较是否有相同的,如果有,则要删除,copy...
- 输出信息
当然,有了STL,这些处理会得到很大的简化。我们可以使用 fstream来代替麻烦的fopen fread fclose, 用vector 来代替数组。最重要的是用 string来代替char * 数组,使用sort排序算法来排序,用unique 函数来去重。听起来好像很不错 。
看看下面代码(例程1):
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
using namespace std;int main(){
ifstream in("name.txt");
string strtmp;vector<string> vect;while(getline(in, strtmp, '/n'))
vect.push_back(strtmp.substr(0, strtmp.find(' ')));sort(vect.begin(), vect.end());vector<string>::iterator it=unique(vect.begin(), vect.end());copy(vect.begin(), it, ostream_iterator<string>(cout, "/n"));
return 0;
}
当然,在这个文本格式中,不用vector而使用map会更有扩充性,例如,还可通过人名找电话号码等等,但是使用了map就不那么好用sort了。你可以用map试一试。
这里string的作用不只是可以存储字符串,还可以提供字符串的比较,查找等。在sort和unique函数中就默认使用了less 和equal_to 函数, 上面的一段代码,其实使用了string的以下功能:
- 存储功能,在getline() 函数中
- 查找功能,在find() 函数中
- 子串功能,在substr() 函数中
- string operator < , 默认在sort() 函数中调用
- string operator == , 默认在unique() 函数中调用
总之,有了string 后,C++的字符文本处理功能总算得到了一定补充,加上配合STL其他容器使用,其在文本处理上的功能已经与perl, shell, php的距离缩小很多了。 因此掌握string 会让你的工作事半功倍。
1 string 使用
其实,string并不是一个单独的容器,只是basic_string 模板类的一个typedef 而已,相对应的还有wstring, 你在string 头文件中你会发现下面的代码:extern "C++" {typedef basic_string <char> string;typedef basic_string <wchar_t> wstring;
} // extern "C++"
string 其实相当于一个保存字符的序列容器,因此除了有字符串的一些常用操作以外,还有包含了所有的序列容器的操作。字符串的常用操作包括:增加、删除、修改、查找比较、链接、输入、输出等。详细函数列表参看附录。不要害怕这么多函数,其实有许多是序列容器带有的,平时不一定用的上。
如果你要想了解所有函数的详细用法,你需要查看basic_string,或者下载STL编程手册。这里通过实例介绍一些常用函数。
1.1 充分使用string 操作符
string 重载了许多操作符,包括 +, +=, <,=,
, [], <<, >>等,正式这些操作符,对字符串操作非常方便。先看看下面这个例子:tt.cpp(例程2)
#include <string>
#include <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;
else
cout << "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>
string strinfo="Winter";
string strlast="Hello " + strinfo + "!";
//你还可以这样:
string strtest="Hello " + strinfo + " Welcome" + " to China" + " !";
- 系统遇到"+"号,发现有一项是string 对象。
- 系统把另一项转化为一个临时 string 对象。
- 执行 operator + 操作,返回新的临时string 对象。
- 如果又发现"+"号,继续第一步操作。
有了操作符以后,assign(), append(), compare(), at()等函数,除非有一些特殊的需求时,一般是用不上。当然at()函数还有一个功能,那就是检查下标是否合法,如果是使用:
string str="winter";// 下面一行有可能会引起程序中断错误str[100]='!';// 下面会抛出异常:throws: out_of_rangecout<<str.at(100)<<endl;
1.2 眼花缭乱的string find 函数
由于查找是使用最为频繁的功能之一,string 提供了非常丰富的查找函数。其列表如下:函数名 | 描述 |
find | 查找 |
rfind | 反向查找 |
find_first_of | 查找包含子串中的任何字符,返回第一个位置 |
find_first_not_of | 查找不包含子串中的任何字符,返回第一个位置 |
find_last_of | 查找包含子串中的任何字符,返回最后一个位置 |
find_last_not_of | 查找不包含子串中的任何字符,返回最后一个位置 |

size_type find_first_of(const basic_string& s, size_type pos = 0)
size_type find_first_of(const charT* s, size_type pos, size_type n)
size_type find_first_of(const charT* s, size_type pos = 0)
size_type find_first_of(charT c, size_type pos = 0)
template <class _CharT, class _Traits, class _Alloc>const basic_string<_CharT,_Traits,_Alloc>::size_typebasic_string<_CharT,_Traits,_Alloc>::npos= basic_string<_CharT,_Traits,_Alloc>::size_type) -1;
find 和 rfind 都还比较容易理解,一个是正向匹配,一个是逆向匹配,后面的参数pos都是用来指定起始查找位置。对于find_first_of 和find_last_of 就不是那么好理解。
find_first_of 是给定一个要查找的字符集,找到这个字符集中任何一个字符所在字符串中第一个位置。或许看一个例子更容易明白。
有这样一个需求:过滤一行开头和结尾的所有非英文字符。看看用string 如何实现:
#include <string>
#include <iostream>
using namespace std;int main(){
string strinfo=" //*---Hello Word!......------";
string strset="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int first = strinfo.find_first_of(strset);
if(first == string::npos) {
cout<<"not find any characters"<<endl;
return -1;
}int last = strinfo.find_last_of(strset);
if(last == string::npos) {
cout<<"not find any characters"<<endl;
return -1;
}cout << strinfo.substr(first, last - first + 1)<<endl;return 0;
}
Hello Word
张三|3456123, 湖南李四,4564234| 湖北王小二, 4433253|北京...
1.3 string insert, replace, erase
了解了string 的操作符,查找函数和substr,其实就已经了解了string的80%的操作了。insert函数, replace函数和erase函数在使用起来相对简单。下面以一个例子来说明其应用。string只是提供了按照位置和区间的replace函数,而不能用一个string字串来替换指定string中的另一个字串。这里写一个函数来实现这个功能:
void string_replace(string & strBig, const string & strsrc, const string &strdst) {string::size_type pos=0;string::size_type srclen=strsrc.size();string::size_type dstlen=strdst.size();while( (pos=strBig.find(strsrc, pos)) != string::npos){
strBig.replace(pos, srclen, strdst);pos += dstlen;}}
#include <string>
#include <iostream>
using namespace std;
int main() {
string strinfo="This is Winter, Winter is a programmer. Do you know Winter?";
cout<<"Orign string is :/n"<<strinfo<<endl;
string_replace(strinfo, "Winter", "wende");
cout<<"After replace Winter with wende, the string is :/n"<<strinfo<<endl;
return 0;
}
Orign string is :This is Winter, Winter is a programmer. Do you know Winter?After replace Winter with wende, the string is :This is wende, wende is a programmer. Do you know wende?
void string_replace(string & strBig, const string & strsrc, const string &strdst) {string::size_type pos=0;string::size_type srclen=strsrc.size();string::size_type dstlen=strdst.size();while( (pos=strBig.find(strsrc, pos)) != string::npos){
strBig.erase(pos, srclen);strBig.insert(pos, strdst);pos += dstlen;}}
2 string 和 C风格字符串
现在看了这么多例子,发现const char* 可以和string 直接转换,例如我们在上面的例子中,使用string_replace(strinfo, "Winter", "wende");
void string_replace(string & strBig, const string & strsrc, const string &strdst)
const charT* c_str() constconst charT* data() constsize_type copy(charT* buf, size_type n, size_type pos = 0) const
- c_str 直接返回一个以/0结尾的字符串。
- data 直接以数组方式返回string的内容,其大小为size()的返回值,结尾并没有/0字符。
- copy 把string的内容拷贝到buf空间中。
const charT* c_str () const{ if (length () == 0) return ""; terminate (); return data (); }
对于c_str() data()函数,返回的数组都是由string本身拥有,千万不可修改其内容。其原因是许多string实现的时候采用了引用机制,也就是说,有可能几个string使用同一个字符存储空间。而且你不能使用sizeof(string)来查看其大小。详细的解释和实现查看Effective STL的条款15:小心string实现的多样性。
另外在你的程序中,只在需要时才使用c_str()或者data()得到字符串,每调用一次,下次再使用就会失效,如:
string strinfo("this is Winter");
...//最好的方式是:foo(strinfo.c_str());//也可以这么用:const char* pstr=strinfo.c_str();foo(pstr);//不要再使用了pstr了, 下面的操作已经使pstr无效了。strinfo += " Hello!";
foo(pstr);//错误!
3 string 和 Charactor Traits
了解了string的用法,该详细看看string的真相了。前面提到string 只是basic_string的一个typedef。看看basic_string 的参数:template <class charT, class traits = char_traits<charT>,class Allocator = allocator<charT> >
class basic_string
{//...
}
就像Steve Donovan在过度使用C++模板中提到的,这些确实有些过头了,要不是系统自己定义了相关的一些属性,而且用了个typedef,否则还真不知道如何使用。
但复杂总有复杂道理。有了char_traits,你可以定义自己的字符串类型。当然,有了char_traits < char > 和char_traits < wchar_t > 你的需求使用已经足够了,为了更好的理解string ,咱们来看看char_traits都有哪些要求。
如果你希望使用你自己定义的字符,你必须定义包含下列成员的结构:
表达式 | 描述 |
---|---|
char_type | 字符类型 |
int_type | int 类型 |
pos_type | 位置类型 |
off_type | 表示位置之间距离的类型 |
state_type | 表示状态的类型 |
assign(c1,c2) | 把字符c2赋值给c1 |
eq(c1,c2) | 判断c1,c2 是否相等 |
lt(c1,c2) | 判断c1是否小于c2 |
length(str) | 判断str的长度 |
compare(s1,s2,n) | 比较s1和s2的前n个字符 |
copy(s1,s2, n) | 把s2的前n个字符拷贝到s1中 |
move(s1,s2, n) | 把s2中的前n个字符移动到s1中 |
assign(s,n,c) | 把s中的前n个字符赋值为c |
find(s,n,c) | 在s的前n个字符内查找c |
eof() | 返回end-of-file |
to_int_type(c) | 将c转换成int_type |
to_char_type(i) | 将i转换成char_type |
not_eof(i) | 判断i是否为EOF |
eq_int_type(i1,i2) | 判断i1和i2是否相等 |
现在默认的string版本中,并不支持忽略大小写的比较函数和查找函数,如果你想练练手,你可以试试改写一个char_traits , 然后生成一个case_string类, 也可以在string 上做继承,然后派生一个新的类,例如:ext_string,提供一些常用的功能,例如:
- 定义分隔符。给定分隔符,把string分为几个字段。
- 提供替换功能。例如,用winter, 替换字符串中的wende
- 大小写处理。例如,忽略大小写比较,转换等
- 整形转换。例如把"123"字符串转换为123数字。
4 string 建议
使用string 的方便性就不用再说了,这里要重点强调的是string的安全性。- string并不是万能的,如果你在一个大工程中需要频繁处理字符串,而且有可能是多线程,那么你一定要慎重(当然,在多线程下你使用任何STL容器都要慎重)。
- string的实现和效率并不一定是你想象的那样,如果你对大量的字符串操作,而且特别关心其效率,那么你有两个选择,首先,你可以看看你使用的STL版本中string实现的源码;另一选择是你自己写一个只提供你需要的功能的类。
- string的c_str()函数是用来得到C语言风格的字符串,其返回的指针不能修改其空间。而且在下一次使用时重新调用获得新的指针。
- string的data()函数返回的字符串指针不会以'/0'结束,千万不可忽视。
- 尽量去使用操作符,这样可以让程序更加易懂(特别是那些脚本程序员也可以看懂)
5 小结
难怪有人说:string 使用方便功能强,我们一直用它!
6 附录
string 函数列表函数名 | 描述 |
begin | 得到指向字符串开头的Iterator |
end | 得到指向字符串结尾的Iterator |
rbegin | 得到指向反向字符串开头的Iterator |
rend | 得到指向反向字符串结尾的Iterator |
size | 得到字符串的大小 |
length | 和size函数功能相同 |
max_size | 字符串可能的最大大小 |
capacity | 在不重新分配内存的情况下,字符串可能的大小 |
empty | 判断是否为空 |
operator[] | 取第几个元素,相当于数组 |
c_str | 取得C风格的const char* 字符串 |
data | 取得字符串内容地址 |
operator= | 赋值操作符 |
reserve | 预留空间 |
swap | 交换函数 |
insert | 插入字符 |
append | 追加字符 |
push_back | 追加字符 |
operator+= | += 操作符 |
erase | 删除字符串 |
clear | 清空字符容器中所有内容 |
resize | 重新分配空间 |
assign | 和赋值操作符一样 |
replace | 替代 |
copy | 字符串到空间 |
find | 查找 |
rfind | 反向查找 |
find_first_of | 查找包含子串中的任何字符,返回第一个位置 |
find_first_not_of | 查找不包含子串中的任何字符,返回第一个位置 |
find_last_of | 查找包含子串中的任何字符,返回最后一个位置 |
find_last_not_of | 查找不包含子串中的任何字符,返回最后一个位置 |
substr | 得到字串 |
compare | 比较字符串 |
operator+ | 字符串链接 |
operator== | 判断是否相等 |
operator!= | 判断是否不等于 |
operator< | 判断是否小于 |
operator>> | 从输入流中读入字符串 |
operator<< | 字符串写入输出流 |
getline | 从输入流中读入一行 |